python 继承 inherit

  

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
31
32
33
34
35
36
37
38
39
40
41
class Animal:
    x=123
    def __init__(self,name):
        self._name=name
        self.__age=10
    @property
    def name(self):
        return self._name
    def shout(self):
        print('Animal shout')
 
class Cat(Animal):
    x='cat'
    def __init__(self,name):
        Animal.__init__(self,name)
        self._name='CAT'+name
        self.__age=20
 
    def shout(self): # override
        print('miao')
        Animal.__init__(self,'abc')
class Garfield(Cat):
    pass
class PersiaCat(Cat):
    # def __init__(self):
    #     self.eyes='blue'
    pass
 
class Dog(Animal):
    def run(self):
        print("Dog Run")
 
tom=Garfield('tom')
print(tom.__dict__) # overload self._name 继承了改名后的Animal和Cat的私有属性__age,但是不能直接访问
print(tom.name) # Animal的property属性,self对象寻找,object->subclass->baseclass
print(tom._name)
print(tom.shout()) # 调用了Animal的__init__方法,进行了属性重定义,Animal中的__init__方法中self.__age=10 => self._Animal__age=10
print(tom._name)
print(tom.__dict__)
print(Cat.__dict__)
print(Animal.__dict__)

  

 

复制代码
class Animal:
    __COUNT=0
    HEIGHT=0
    NAME='uiop'
    def __init__(self,age,weight,height):
        self.__COUNT+=1
        self.age=age
        self.__weight=weight
        self.HEIGHT=height

    def eat(self):
        print('{} eat'.format(self.__class__.__name__))

    def __getweight(self):
        print(self.__weight)

    def getname(self):
        return self.NAME
    @classmethod
    def showcount1(cls):
        print(cls.__COUNT)

    @classmethod
    def __showcount2(cls):
        print(cls.__COUNT)

class Cat(Animal):
    NAME='cat class'
    __COUNT='zxc'
    # def getweight(self): getweight 获取不到对象的_Cat__weight属性,因为父类做了隐藏替换
    #     return self.__weight

c=Cat(3,5,15)
c.eat()
print(c.HEIGHT)
print(Animal.__dict__)
c.showcount1() # 此 classmethod传递的cls为Cat,但是Animal中showcount1的__COUNT已经
被替换成_Animal__COUNT(私有属性),所以取值为Animal中的__COUNT,不会取Cat的__COUNT print(c._Cat__COUNT) print(c.getname()) # object寻找时,虽然为父类的方法,但是传递的对象为Cat object,寻找顺序为子类
->父类,区别于classmethod # print('{}'.format(Animal.__dict__)) # print('{}'.format(Cat.__dict__)) # print(c.__dict__) # print(c.getweight()) print(c.__class__.mro()) print(c.__class__.__mro__) # method resolution order print(Cat.__bases__) # 类的基类列表 print(Cat.__base__) # 类的基类 print(Cat.__subclasses__()) print(Animal.__subclasses__()) # 类的子类列表 print(Animal.__dict__)
复制代码

 

posted @   ascertain  阅读(256)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示