所以我正在学习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
您应该向任何希望将其计为
object
方法的函数提供self
。如果不想提供self
,该函数可以是static
函数(这意味着它不依赖于对象本身的类型)。然后,您需要通过@staticmethod
decorator澄清该函数构造类时,定义的方法必须将实例作为第一个参数。类实例被称为
self
(尽管您可以随意调用它):当您定义
__init__
时就会看到这一点。所有其他功能都是这样工作的。当你这样称呼他们的时候这类似于:
它只是针对实例调用方法,将自动为您传递
self
。在实例内调用该方法时,需要指定要调用的实例,只是调用self
而不是instance
:同样,这与调用相同:
因为
instance
被传入,因此可以使用适当的方法调用它*未用
@staticmethod
或@classmethod
修饰的所有其他函数您需要将
self
添加到方法调用和声明中:或
您需要将
cantBeStudent
作为静态方法调用,如下所示:相关问题 更多 >
编程相关推荐