抱歉,这是我第一次问问题,我的格式可能不正确。我不确定在不创建类实例的情况下从类调用函数的语法。对于代码:
class A_Class:
var = 10
def __init__(self):
self.num = 12
def print_12(self):
return 12
我怎么能打电话
print(A_Class.var)
让控制台打印出值10,但是如果我要呼叫
print(A_Class.num)
然后我得到了错误:
AttributeError: type object 'A_Class' has no attribute 'num'
如果我尝试致电
print(A_Class.print_12)
然后控制台打印:
<function A_Class.print_12 at 0x039966F0>
不是值12
我对如何从类中调用函数感到困惑。
答案 0 :(得分:4)
var
是Class
变量,而num
是实例变量,例如:
class A_Class:
var = 10
def __init__(self):
self.num = 12
def print_12(self):
return 12
a = A_Class()
作为类变量,它属于该类,您可以调用它。
print(A_Class.var)
>> 10
作为实例变量,必须先实例化它,然后才能访问值,这就是self
(self
没有特殊含义,可以是任何东西,但是总是实例的第一个参数的原因方法),并在特殊的__init__
方法中对其进行初始化。
a = A_Class()
print(a.num)
>> 12
最后,您要打印返回的值,因此必须调用它,例如:
var = a.print_12()
print(var)
>> 12
由于您之前缺少括号,它是实例方法本身,因此没有返回任何值。
答案 1 :(得分:2)
要在@BernardL上扩展有关类变量和实例变量之间差异的出色答案,我想补充一下,这是我从PyTricks时事通讯中获得的,它可能有助于回答关于print(A_Class.print_12)
的问题。
# @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)"
答案 2 :(得分:0)
这是因为您在类根级别定义的是static
变量或方法。
该类中的方法本身也是对象,因此,如果print
它们将返回对象type
和内存地址,因为没有定义打印(或转换为{{1})的方法})对象(通常用string
指定)。