class Dog:
def __init__(self, name, age):
self.name= name
self.age= age
def __getattr__(self, key):
return f"{key} not found"
dog = Dog("taidi",5)
print(dog.name) # taidi
print(dog.age) # 5
print(dog.breed) # breed not found
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
class Dog:
def __init__(self, name, age):
self.name= name
self.age= age
def __getattribute__(self, key):
return f"{key} not found"
dog = Dog("taidi",5)
print(dog.name) # name not found
print(dog.age) # age not found
print(dog.breed) # breed not found
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
3、super().__init__() 的另一种写法
class Animal:
def __init__(self, name, age):
self.name= name
self.age= age
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed= breed
1.
2.
3.
4.
5.
6.
7.
8.
等价于:
class Animal:
def __init__(self, name, age):
self.name= name
self.age= age
class Dog(Animal):
def __init__(self, name, age, breed):
Animal.__init__(self, name, age)
self.breed= breed
class Animal: pass
class Dog(Animal): pass
class Cat(Animal): pass
class GermanSheperd(Dog): pass
print(Animal.__subclasses__())
# [<class '__main__.Dog'>,<class '__main__.Cat'>]
1.
2.
3.
4.
5.
6.
不过,.__subclasses__() 只能检查直接子类。
5、多重集成时,同名函数,子类用的是哪一个?
class A:
def test(self):
print("A")
class B:
def test(self):
print("B")
class C(A, B):
pass
C().test() # A
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
A 和 B 都有 test 方法,那么 C 到底集成了哪一个呢?在 Python 中,最左边的类优先。
在这里,A 是最左边的父类,因此 A 的 test 方法被集成。
多充继承让人困惑,不用为好。
6 __invert__ 魔法函数
class Dog:
def __invert__(self):
return "test"
dog = Dog()
print(~dog) # test
1.
2.
3.
4.
5.
~ 运算符代表“按位非”,通常用于反转内容。一个更有意义的例子如下:
class Coordinate:
def __init__(self, x, y):
self.x= x
self.y= y
def __str__(self):
return f"({self.x}, {self.y})"
def __invert__(self):
return Coordinate(-self.x,-self.y)
a = Coordinate(3,4)
b =~a
print(a, b) # (3,4)(-3,-4)
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
7、不使用 class 来创建类
def init(self, name, age):
self.name= name
self.age= age
def bark(self):
print("woof")
Dog = type("Dog",(),{"__init__":init,"bark":bark})
dog = Dog("taidi",10)
print(dog.name)
print(dog.age)
# taidi
# 10