为什么我不能在python中从同一个类运行方法?

2024-10-03 04:31:32 发布

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

主题结束

所以我正在学习python中的OOP,并想测试我的知识。我就是这么做的

class Student:
    def cantBeStudent():
        print('You don\' classify as a stududent')

    def __init__(self, age, education):
        self.age = age
        self.education = education
        if (self.age < 16) or (self.education < 3):
            cantBeStudent()


student1 = Student(age=18, education=2)

当我尝试调用cantBeStudent()时,我得到name\u错误。它说cantBeStudent没有定义。我在谷歌上找不到我的答案,所以我来到这里

编辑:当我注释掉整个cantBeStudent时,我在definit


Tags: selfyou主题agedefasstudentoop
3条回答

您应该向任何希望将其计为object方法的函数提供self。如果不想提供self,该函数可以是static函数(这意味着它不依赖于对象本身的类型)。然后,您需要通过@staticmethoddecorator澄清该函数

构造类时,定义的方法必须将实例作为第一个参数。类实例被称为self(尽管您可以随意调用它):

class X:
    def __init__(self, number):
        self.number = number

    def add_number(self, arg):
        self.number += arg

当您定义__init__时就会看到这一点。所有其他功能都是这样工作的。当你这样称呼他们的时候

instance = X(1)

instance.add_number(3)

这类似于:

instance = X(1)

X.add_number(instance, 3)

它只是针对实例调用方法,将自动为您传递self。在实例内调用该方法时,需要指定要调用的实例,只是调用self而不是instance

class X:
    ~snip~
    def add_number(self, arg):
        self.number += arg

    def increment_number(self):
        # note the self.<method>
        self.add_number(1)

同样,这与调用相同:

instance = X(1)

X.increment_number(instance)

因为instance被传入,因此可以使用适当的方法调用它

*未用@staticmethod@classmethod修饰的所有其他函数

您需要将self添加到方法调用和声明中:

class Student:
    def cantBeStudent(self): # need self
        print('You don\' classify as a stududent')

    def __init__(self, age, education):
        self.age = age
        self.education = education
        if (self.age < 16) or (self.education < 3):
            self.cantBeStudent() # need self


student1 = Student(age=18, education=2)

您需要将cantBeStudent作为静态方法调用,如下所示:

class Student:
    def cantBeStudent(): # no self as first argument, therefore static method
        print('You don\' classify as a stududent')

    def __init__(self, age, education):
        self.age = age
        self.education = education
        if (self.age < 16) or (self.education < 3):
            Student.cantBeStudent() # because declaration has no self,
                                    # cantBeStudent belongs to entire Student class


student1 = Student(age=18, education=2)

相关问题 更多 >