python核心-面向对象-私有化属性

文章探讨了Python中类的属性使用,包括公有属性、保护属性和私有属性,以及它们在继承中的行为。同时,提到了初始化方法`__init__`的作用,以及如何通过`isinstance`函数验证数据类型。示例代码展示了属性访问权限的限制和错误处理。

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

x公有属性 

 

class Animal:
    x = 10
    def test(self):
        print(Animal.x)
        print(self.x)
    pass

class Dog(Animal):
    def test2(self):
        print(Dog.x)
        print(self.x)
    pass


# 测试代码
a = Animal()
# a.test()

b = Dog()
# b.test2()

# print(Animal.x)
# print(Dog.x)
# print(a.x)
# print(b.x)

a = 666

 

 

# import 私有化属性
#
# print(私有化属性.a)

from 私有化属性 import *
print(a)

_x受保护属性 

 

# class Animal:
#     _x = 10
#     def test(self):
#         print(Animal._x)
#         print(self._x)
#     pass
#
# class Dog(Animal):
#     def test2(self):
#         print(Dog._x)
#         print(self._x)
#     pass


# 测试代码
# a = Animal()
# a.test()

# b = Dog()
# b.test2()

# print(Animal._x)
# print(Dog._x)
# print(a._x)
# print(b._x)



__all__ = ["_a"]
_a = 666
# import 私有化属性
#
# print(私有化属性._a)

from 私有化属性 import *
print(_a)      # NameError: name '_a' is not defined

_xx 私有属性

 

class Animal:
    __x = 10
    def test(self):
        print(Animal.__x)
        print(self.__x)
    pass
#
class Dog(Animal):
    def test2(self):
        print(Dog.__x)
        print(self.__x)
    pass


# 测试代码
a = Animal()
# a.test()

b = Dog()
# b.test2()   #AttributeError: type object 'Dog' has no attribute '_Dog__x'

# print(Animal.__x)  #AttributeError: type object 'Animal' has no attribute '__x'
# print(Dog.__x)  #
# print(a.__x)    #
# print(b.__x)    #
#
__all__ = ["__a"]
__a = 666
import 私有化属性

print(私有化属性.__a)

from 私有化属性 import *
print(__a)      # NameError: name '_a' is not defined

 应用场景

class Person():
    #  主要作用,当我们创建好一个实例对象后,会自动调用这个方法,来初始化这个对象
    def __init__(self):
        self.age = 18

    def setAge(self, value):
        if isinstance(value, int) and 0 < value < 200:
            self.__age = value
        else:
            print("你输入额数据有问题,请重新输入")
    def getAge(self):
        return self.__age

p1 = Person()
p1.setAge(200)
# print(p1.getAge())

# p2 = Person()
# p2.age

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值