python面向对象02_类属性&类方法&静态方法
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
| class Dog: dogs=[] @classmethod def num_of_dogs(cls): return len(cls.dogs) @classmethod def biggest(cls): max_height=0 for d in cls.dogs: if(d.height>d.height): max_height=d.height return max_height @staticmethod def intro(): print("Dog is human's best friend") def __init__(self,name,height,power): self.name=name self.height=height self.power=power self.blood=10 Dog.dogs.append(self) print(f'{self.name}出生了') def bark(self): print(f'name:{self.name},blood:{self.blood}') def attack(self,dog2): dog2.blood=dog2.blood-self.power
|
1 2 3 4 5 6
| dog1=Dog('大黄',0.5,4) dog2=Dog('大黑',0.4,3)
print(Dog.num_of_dogs()) print(dog1.num_of_dogs()) dog1.intro()
|
大黄出生了
大黑出生了
2
2
Dog is human's best friend
__main__.Dog
[<__main__.Dog at 0x20332f67d30>, <__main__.Dog at 0x20332f743d0>]