面向对象(二)

本文探讨了Python中面向对象编程的私有化特性,解释了如何通过双下划线实现属性私有化,并展示了__dict__的使用。同时,介绍了`property`装饰器的应用,使类的方法能够像属性一样被调用,增强了代码的可读性。此外,还讨论了`property`与私有化属性的组合使用,以及类中的静态和类方法,强调了类方法在不需要实例化时的作用。

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

类中属性的私有化:

在类中属性前加上双下滑线就是私有化的属性了,不能在类外直接通过类名调用

class Dog:
    __role = 'dog'

d = Dog()
print(Dog.__role)
报错!

我们可以用__dict__看看Dog中有那些属性看看__role变成了什么

class Dog:
    __role = 'dog'


print(Dog.__dict__)

{'__module__': '__main__', '_Dog__role': 'dog', '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None}

我们可以看到__role属性变成了_Dog__role
当我们用_Dog__role调用看看

class Dog:
    __role = 'dog'
print(Dog._Dog__role)

dog

我们可以看到role可以被调用了。所以在python中绝对的私有化是没有的我们总能想到方法调用。

python中的私有化我感觉可以这么理解当你的在变量名前添加了双下划线就等于把变量名改为了 _当前类名__属性名

property

装饰器
可以将类中的方法伪装成一个属性
用法如下

from math import pi
class Cricle:
    def __init__(self, r):
        self.r = r

    def perimeter(self):
        return 2 * pi * self.r

    def sqare(self):
        return pi * self.r ** 2

在上述的代码中我们定义了一个圆类我们可以实例化一个圆,每次我们想要得到其周长和面积是我们都可以调用他们的方法,但是我们可以这么认为面积和周长是圆的固有属性而不是方法,我们怎么样可以跟调用属性一样调用方法呢,python还是厉害.有个property的装饰器可以用到

from math import pi
class Cricle:
    def __init__(self, r):
        self.r = r

    @property
    def perimeter(self):
        return 2 * pi * self.r

    @property
    def sqare(self):
        return pi * self.r ** 2

现在我们可以直接跟调用属性一样调用方法了

c1 = Cricle(5)
print(c1.perimeter)

输出:
31.41592653589793

property和私有化属性的组合使用

class Goods:
    __discount = 0.8
    def __init__(self, name, price)
        self.name = name
        self.__price = price

    @property
    def price(self):
        return self.__price * __discount

    @price.setter
    def price(self, new_price):
        self.__price = new_price

    @price.deleter
    def price(self):
        print('删除了')

apple = Goods(5)
print(apple.price)
apple.price = 8
print(apple.price)
del apple.price

输出结果:
4.0
6.4
删除了!

NB!

类中的静态和类方法

class Goods:
    __discount = 0.8

    @classmethod
    def modify_discount(cls, new_discount):
        Goods.__discount = new_discount

类方法的调用不需要实例化直接用类名调用,cls代表的是Goods类和self差不多都代表本身。
什么时候用类方法:当需要使用类中的静态方法,且不需要和对象相关的任何操作时


静态方法和普通方法没什么大的区别

class A:
    @staticmethod
    def func(args): # 静态方法
        print('123')
A.func(args)

可以通过类名直接带调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值