Syntax confusion during calling of functions from python classes
本问题已经有最佳答案,请猛点这里访问。
抱歉,这是我第一次问问题,我的格式可能有误。我不确定在不创建类实例的情况下从类调用函数的语法。对于代码:
1 2 3 4 5 6 7 8 | class A_Class: var = 10 def __init__(self): self.num = 12 def print_12(self): return 12 |
我怎么能打电话来
1 | print(A_Class.var) |
让控制台打印出值10,但如果我要打电话
1 | print(A_Class.num) |
然后我得到错误:
1 | AttributeError: type object 'A_Class' has no attribute 'num' |
如果我想打电话
1 | print(A_Class.print_12) |
然后控制台打印:
1 | <function A_Class.print_12 at 0x039966F0> |
而不是值12
我对如何从类中调用函数感到困惑。
1 2 3 4 5 6 7 8 9 | class A_Class: var = 10 def __init__(self): self.num = 12 def print_12(self): return 12 a = A_Class() |
作为一个类变量,它属于该类,您可以调用它。
1 2 | print(A_Class.var) >> 10 |
作为一个实例变量,在访问值之前必须先实例化它,这就是为什么
1 2 3 | a = A_Class() print(a.num) >> 12 |
最后,您要打印返回值,因此必须调用它,例如:
1 2 3 | var = a.print_12() print(var) >> 12 |
正如您之前丢失了括号一样,它是实例方法本身,因此没有返回任何值。
为了进一步讨论@bernardl关于类变量和实例变量之间差异的最佳答案,我想补充一点,这是我从PyTricks时事通讯中得到的,这可能有助于回答您关于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | # @classmethod vs @staticmethod vs"plain" methods # What's the difference? class MyClass: def method(self): """ Instance methods need a class instance and can access the instance through `self`. """ return 'instance method called', self @classmethod def classmethod(cls): """ Class methods don't need a class instance. They can't access the instance (self) but they have access to the class itself via `cls`. """ return 'class method called', cls @staticmethod def staticmethod(): """ Static methods don't have access to `cls` or `self`. They work like regular functions but belong to the class's namespace. """ return 'static method called' # All methods types can be # called on a class instance: >>> obj = MyClass() >>> obj.method() ('instance method called', <MyClass instance at 0x1019381b8>) >>> obj.classmethod() ('class method called', <class MyClass at 0x101a2f4c8>) >>> obj.staticmethod() 'static method called' # Calling instance methods fails # if we only have the class object: >>> MyClass.classmethod() ('class method called', <class MyClass at 0x101a2f4c8>) >>> MyClass.staticmethod() 'static method called' >>> MyClass.method() TypeError: "unbound method method() must be called with MyClass" "instance as first argument (got nothing instead)" |
这是因为您在类根级别中定义的是一个
类中的方法也是对象本身,因此,如果