对于Python中类和实例变量的理解(class and Instance variables)

class Dog:
    kind = 'canine'
    def __init__(self, name):
        self.name = name

d = Dog('Fibo')
e = Dog("Katy")
if __name__ == '__main__':
    print(d.kind)
    print(e.kind)
    print(d.name)
    print(e.name)
#输出结果为
canine
canine
Fibo
Katy
class Dog:
    kind = 'cnaine'
    tricks = []
    def __init__(self, name):
        self.name = name
    def add_tricks(self, trick):
        self.tricks.append(trick)

if __name__ =='__main__':
    d = Dog('Polo')
    e = Dog('Katy')
    print(d.add_tricks("Play soccer"))
    print(e.add_tricks("Play basketball"))
    print(d.tricks)

#输出结果
None
None
['Play soccer', 'Play basketball']
#对于上述None,因为add_tricks返回的值为None.以及tricks列表是一个全局列表。

#实例二
class Dog:
    kind = 'cnaine'
    
    def __init__(self, name):
        self.tricks = []
        self.name = name
    def add_tricks(self, trick):
        self.tricks.append(trick)

if __name__ =='__main__':
    d = Dog('Polo')
    e = Dog('Katy')
    print(d.add_tricks("Play soccer"))
    print(e.add_tricks("Play basketball"))
    print(d.tricks)

#输出结果
None
None
['Play soccer']
['Play basketball']

 

你可能感兴趣的:(Python学习)