简体   繁体   English

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

[英]Why can't i run a method from the same class in python?

Topic Closed话题关闭

So I'm learning OOP in python and wanted to test my knowledge.所以我在 python 中学习 OOP 并想测试我的知识。 That's what i did这就是我所做的

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)

I get name_error when i try to call cantBeStudent().当我尝试调用 cantBeStudent() 时出现 name_error。 It says that cantBeStudent is not defined.它说 cantBeStudent 没有定义。 I can't find my answer on google so I came here.我在谷歌上找不到我的答案,所以我来到了这里。

Edit: Also when i comment out whole cantBeStudent i get SyntaxError on def init编辑:另外,当我注释掉整个 cantBeStudent 时,我在 def init上得到 SyntaxError

You need to add self to the method invocation and declaration:您需要将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)

OR或者

You need to invoke cantBeStudent as a static method like so:您需要像这样调用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)

When you construct a class, methods that you define must take the instance as the first argument.当您构造一个类时,您定义的方法必须将实例作为第一个参数。 The class instance is referred to as self (though you could call it anything you wanted):类实例被称为self (尽管您可以随意称呼它):

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

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

You see this when you define __init__ .当您定义__init__时,您会看到这一点。 All other functions* work this way as well.所有其他功能*也以这种方式工作。 When you call them like当你这样称呼他们时

instance = X(1)

instance.add_number(3)

It's analogous to doing:这类似于做:

instance = X(1)

X.add_number(instance, 3)

It's just calling the method against the instance will automatically pass self for you.它只是针对实例调用方法会自动为您传递self When you call that method inside the instance, you need to specify the instance you are calling against, it's just this is called self instead of instance :当您在实例内调用该方法时,您需要指定您正在调用的实例,它只是被称为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)

Again, this would be identical to the call:同样,这与调用相同:

instance = X(1)

X.increment_number(instance)

Because the instance gets passed in so that it can be called with the appropriate method因为instance被传入,以便可以使用适当的方法调用它

* All other functions that are not decorated with @staticmethod or @classmethod * 所有其他没有用@staticmethod@classmethod

You should provide self to any function that you want it to be counted as an object 's method.您应该将self提供给您希望将其视为object方法的任何函数。 If you do not want to provide self that function could be a static function (which means it does not rely on the type of the object itself).如果您不想提供self ,则该函数可以是static函数(这意味着它不依赖于对象本身的类型)。 Then, you need to clarify that function, by @staticmethod decorator.然后,您需要通过@staticmethod装饰器来阐明该功能。

You missed self parameter on cantBeStudent method and when call it from contructor, it should be self.canBeStudent.你错过了 cantBeStudent 方法上的 self 参数,当从构造函数调用它时,它应该是 self.canBeStudent。 Like this:像这样:

class Student:
    def cantBeStudent(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()

The purpose of self in Python: What is the purpose of the word 'self', in Python? Python 中 self 的目的:Python 中“self”这个词的目的是什么?

Add self on the function cantBeStudent在函数cantBeStudent上添加 self

class Student:
    def cantBeStudent(self):
        print("You don't 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()

That happens because you need to specify that the function is contained in the same class of 'self'发生这种情况是因为您需要指定该函数包含在同一类“self”中

If you would done in this way it would had worked:如果你这样做,它会起作用:

def cantBeStudent():
        print("You don't classify as a stududent")

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

The main difference is that in the first case, the function is inside the class Student, in the other case the function is out of the class, so don't need the 'self'主要区别在于,在第一种情况下,函数在类 Student 内,在另一种情况下,函数在类外,因此不需要“self”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM