时间:2021-07-01 10:21:17 帮助过:6人阅读
class Kls(object):
def __init__(self, data):
self.data = data
def printd(self):
print(self.data)
ik1 = Kls('arun')
ik2 = Kls('seema')
ik1.printd()
ik2.printd()
看了很多解释,感觉还是这个比较清楚@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).
投票最高的回答比较基础,稍微进阶一点的看下下面的stackoverflow上的回答,回答top1与top2class Utility(object):
@staticmethod
def list_all_files_in_dir(dir_path):
...
我不制造答案,我只是答案的搬运工~~~from random import choice
COLORS = ['Brown','Black','Golden']
class Animal(object):
def __init__(self,color):
self.color = color
@classmethod
def make_baby(cls):
color = choice(COLORS)
print cls
return cls(color)
@staticmethod
def speak():
print 'Rora'
class Dog(Animal):
@staticmethod
def speak():
print "Bark!"
@classmethod
def make_baby(cls):
print "making dog baby!"
print cls
return super(Dog,cls).make_baby()
class Cat(Animal):
pass
d = Dog('Brown')
print d.color
pup = d.make_baby()
pup
print pup.color
注意 static method 和 class method 在继承中的区别