为什么how_many中要用cls作为一个参数,不能够直接返回Person.__count吗?
class Person(object): __count=0 def __init__(self,name): self.name = name Person.__count =+1 @classmethod def how_many(): return Person.__count
class Person(object): __count=0 def __init__(self,name): self.name = name Person.__count =+1 @classmethod def how_many(): return Person.__count
2015-05-04
谢谢@Apalapucia 现在搞懂了~~
之前一直以为方法(类方法和实例方法)里的self参数是不能只能用'self'这个串的,其实换成其他的也可以,只要是第一个参数,python就把它当self来用。
>>> class Person(object):
def __init__(a, name): #用a替换的self,但与使用self没有区别
a.name = name
>>> p = Person('xxx')
>>> p.name
'xxx'>>> class Person(object):
__count = 0
def __init__(self, name):
self.name = name
Person.__count += 1
@classmethod
def how_many(P): #@classmethod也是一样的,但第一个参数必须有,楼主给定代码how_many无
return P.__count #参,我测试了下,会报错 TypeError: how_many() takes 0 positional
>>> a = Person('a') #arguments but 1 was given
>>> b = Person('b')
>>> Person.how_many()
2举报