Python 继承关系

Posted 缥缈映苍穹

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 继承关系相关的知识,希望对你有一定的参考价值。

class Base:
    def chi(self):
        print("我会吃")


# 派生类  => 子类
class Foo(Base): # 这个类继承了Base类. Foo类是对Base的一个扩展
    def he(self):
        print("我会喝")

f = Foo()
f.chi()
f.he()


class Cat:  # 父类 => 基类  => 超类
    def catch_mouse(self):
        print("猫可以抓老鼠")

class BosiCat(Cat):  # 子类 => 派生类
    pass


class Foo:
    pass


print(hash(Foo)) # 可哈希
print(hash(Foo()))

# 我们写好的类和创建的对象默认都是可哈希的


# 去掉可哈希
class Foo:
    __hash__ = None # 当前类的对象不可哈希


print(hash(Foo)) # 可哈希
print(hash(Foo())) # TypeError: unhashable type: ‘Foo‘


class Foo:
    def chi(self, food):
        print("我爱吃鱼和", food)

class Bar:
    def chi(self, food):
        print("我爱吃肉和", food)

dic = {Foo: "鸡蛋", Bar: "香肠"}

for k, v in dic.items():
    k().chi(v)

# 类名  => 变量名 -> 为了今天作业

def func():
    pass

an = func

an()



class Base:
    def __init__(self, num):
        self.num = num
    def func1(self):
        print(self.num)
class Foo(Base):
    pass
obj = Foo(123)
obj.func1()



class Base:
    def __init__(self, num):
        self.num = num
    def func1(self):
        print(self.num)

class Foo(Base):
    def func1(self):
        print("Foo. func1", self.num)

obj = Foo(123)
obj.func1()


class Base:
    def __init__(self, num):
        self.num = num
    def func1(self):
        print(self.num)
        self.func2()
    def func2(self):
        print("Base.func2")

class Foo(Base):
    def func2(self):
        print("Foo.func2")
obj = Foo(123)
obj.func1()



class Base:
    def __init__(self, num):
        self.num = num

    def func1(self):
        print(self.num)
        self.func2()

    def func2(self):
        print(111, self.num)

class Foo(Base):
     def func2(self):
        print(222, self.num)

lst = [Base(1), Base(2), Foo(3)]
for obj in lst:
 obj.func2()



class Base:
    def __init__(self, num):
        self.num = num
    def func1(self):
        print(self.num)
        self.func2()
    def func2(self):
        print(111, self.num)

class Foo(Base):
    def func2(self):
        print(222, self.num)

lst = [Base(1), Base(2), Foo(3)]
for obj in lst:
    obj.func1()

  

以上是关于Python 继承关系的主要内容,如果未能解决你的问题,请参考以下文章

01月11日 四周四次Python基础进阶

python中类与对象之继承

python开发-面向对象的继承与派生

Python OOP-2

python基础之继承原理,多态与封装

python基础 继承