Python中的类导入和赋值

2024-04-26 05:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在下面创建一个类,请有人解释一下创建实例的正确方法,并传递参数。我原以为我可以在开始的时候把最初的论点传过来,但似乎无法让它起作用。下面是该类的一个示例:

Class Course(object):
    """
    Represents a University course
    """

    def _init_(self, name, teacher, description):
        self.name = name
        self.teacher= price
        self.description = description

    def _str_(self):
        return "{name} ({desc}): {teacher:}".format(name=self.name,
                desc=self.description, teacher=self.teacher)

所以在我的程序中,我想创建一个实例,我认为我是通过使用class = Course()之类的东西来创建的。你知道吗

但是,难道没有办法同时启动这3个变量吗?类似于class('Math101', 'Dr. Know Nothing', 'Learning is Fun')的东西?你知道吗

然后我就可以print class从类中获得所需的输出字符串?如果我需要导入模块或类,我可能会在某个地方丢失一个导入,这也会让我感到困惑,我需要做的只是初始的class = Course()?你知道吗


Tags: 实例方法nameself示例参数objectdef
2条回答

首先,你需要加倍强调:

def __init__(self, ...):
    // whatever

def __str__(self, ...):
    // whatever

Classclass Course小写,而不是Class Course。你知道吗

现在你可以这样使用你的类:

course = Course('Math101', 'Dr. Know Nothing', 'Learning is Fun') 
print course

必须用双下划线声明special methods__init__,而不是_init_。然后,在创建对象时,必须传递如下参数:course1 = Course(...parameters...)

class Course(object):
    """
    Represents a University course
    """
    def __init__(self, name, teacher, description):
        self.name = name
        self.teacher = teacher
        self.description = description

    def __str__(self):
        return "{name} ({desc}): {teacher:}".format(name = self.name,
                desc = self.description, teacher = self.teacher)

course1 = Course('Math101', 'Dr. Know Nothing', 'Learning is Fun')
print course1

输出:

Math101 (Learning is Fun): Dr. Know Nothing

备注:

  • 创建类的Python关键字是class,而不是Class。Python对关键字是区分大小写的。

  • 您将price分配给self.teacher,这将导致错误,因为price没有在任何地方声明。我想这只是一个拼写错误。您可以改用self.teacher = teacher

  • 不能使用Python关键字(保留名称)作为变量名,因为如果这样做,将隐藏这些关键字,这将导致问题。

相关问题 更多 >