python面向对象继承调用

本文深入探讨了Python中继承的三种方式:继承类的方法、属性赋值以及在基类基础上新增方法。同时,详细解析了装饰器的使用,包括如何通过装饰器使类对象调用属性时无需加括号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、继承跟属性赋值super方法调用

class A(object): # 基类

    class_a = 20

    def __init__(self):
        self.a = 10 # 实例对象

    def a_nherit(self):
        str = '继承的方式'
        print("a_nherit%s,"% str)

    def a_object(self): # 方法
        str = '属性赋值的方式'
        print("a_object%s"% str)

    def a_super(self): # 方法
        str = '父类的基类'
        print("a_super%s"% str)

print('*'*10+'方法一'+'*'*10)
# 方法一:继承的方式
class B(A): #
    def b_print(self):
        print('b_print')
B().a_nherit()

print('*'*10+'方法二'+'*'*10)
# 方法二:属性赋值的方式
class B(object):
    object_a = A()

    def b_print(self):
        print('b_print')
B.object_a.a_object()

print('*'*10+'方法三'+'*'*10)
# 方法三:在基类的基础上,在原来的基础上新增
class C(A):
    def a_super(self):
        super().a_super()
        str = "在父类的基础上新增"
        print("add_date%s" % str)

输出结果

**********方法一**********
a_nherit继承的方式

**********方法二**********
a_object属性赋值的方式

**********方法三**********
a_super父类的基类
add_date在父类的基础上新增

2、装饰器的调用

class A():
    def __init__(self):
        pass

    def a_property(self):
        print('a_property')


# 不加括号的话是当成是属性来使用
A().a_property

打印结果

结果为空


Process finished with exit code 0

3、类对象调用属性不加括号可以用装饰器(@property)

class A():
    def __init__(self):
        pass

    @property
    def a_property(self):
        print('a_property')

A().a_property

打印结果

a_property

Process finished with exit code 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值