Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >
1
2
3
#类方法,为了使用类属性
#可以用过类名调用,也可以通过实例名调用
#类方法为了访问类变量
1
#静态方法,不需要传入实例或者类作为第一个参数
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:
#num_of_dogs=0
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): # 1.魔方方法与普通方法的区别在于触发 # 2.self就是一个代词,因为还没有被实例化,所以用这个代词
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
1
type(Dog.dogs[0])
__main__.Dog
1
dog1.dogs
[<__main__.Dog at 0x20332f67d30>, <__main__.Dog at 0x20332f743d0>]

评论