Python类的成员

类的成员

类的内置成员

code:_10class_buildin_member.py

# *********************************************************
"""
类的内置成员:
    __dict__:获取当前类的所有成员
    __name__:获取当前类的名称
    __bases__:获取当前类的直接父类
    __base__:获取当前类的上一级父类
    __module__:获取当前类所在的文件,如果是当前文件,则返回__main__
    __mro__:获取当前类的继承关系列表(包括直接或间接父类)
"""


class father:
    def eat(self):
        print("大口吃饭~")


class mother:
    def eat(self):
        print("小口吃饭~")


class child(father,mother):
    """这是一个类说明doc"""
    def eat(self):
        super().eat()  # 这里会调用第一个父类的方法
        print("又哭又闹吃饭饭~")


Jasmine = child()
print(f"child.__dict__ = {child.__dict__}")
print(f"Jasmine.__dict__ = {Jasmine.__dict__}")
print(f"child.__name__ = {child.__name__}")
# print(f"Jasmine.__name__ = {Jasmine.__name__}")  # not allowed
print(f"child.__doc__ = {child.__doc__}")
print(f"child.__bases__ = {child.__bases__}")
# print(f"Jasmine.__bases__ = {Jasmine.__bases__}")  # not allowed
print(f"child.__base__ = {child.__base__}")
# print(f"Jasmine.__base__ = {Jasmine.__base__}")  # not allowed
print(f"child.__module__ = {child.__module__}")
print(f"Jasmine.__module__ = {Jasmine.__module__}")
print(f"child.__mro__ = {child.__mro__}")
# print(f"Jasmine.__mro__ = {Jasmine.__mro__}")  # not allowed

运行结果:

E:\Programs_Way\Python\python.exe D:/Prj/_PythonSelf/Object_oriented_programming/_10class_buildin_member.py
child.__dict__ = {'__module__': '__main__', '__doc__': '这是一个类说明doc', 'eat': <function child.eat at 0x000002632A4F9280>}
Jasmine.__dict__ = {}
child.__name__ = child
child.__doc__ = 这是一个类说明doc
child.__bases__ = (<class '__main__.father'>, <class '__main__.mother'>)
child.__base__ = <class '__main__.father'>
child.__module__ = __main__
Jasmine.__module__ = __main__
child.__mro__ = (<class '__main__.child'>, <class '__main__.father'>, <class '__main__.mother'>, <class 'object'>)

Process finished with exit code 0

方法的分类

  • 对象方法
  • 类方法
  • 绑定类方法
  • 静态方法

code:_11method_classification.py

# ****************************************************
"""
方法的分类:
    1.对象方法:
    特征:
        1.在类中定义的方法,含有self参数
        2.只能使用对象进行调用
    2.类方法 cls @classmethod
    特征:
        1.在类中定义的方法使用了 装饰器@classmethod 进行了装饰
        2.不需要实例化对象,直接使用类进行调用(也可以使用对象调用,但是传递的参数依然是对应的类)
        3.含有cls形参,及传递一个类
    3.绑定类方法
    特征:
        1.不传递任何对象或类,可以传递其他参数
        2.使用类调用,不能使用对象调用
    4.静态方法
    特征:
        1.不传递任何对象或类,可以传递其他参数
        2.使用装饰器 @staticmethod 装饰
        3.可以使用类或对象调用
"""


class test:
    def obj_method(self,a,b):
        print("This is a object method!",a,b)

    @classmethod
    def class_method(cls,a,b):
        print(cls)
        print("This is a class method!",a,b)

    def bind_method(a,b):
        print("This is a bind method!",a,b)

    @staticmethod
    def static_method(a,b):
        print("This is a static method!", a, b)


data = test()
data.obj_method(1,2)
data.class_method(1,2)
test.class_method(1,2)
test.bind_method(1,2)
data.static_method(1,2)
test.static_method(1,2)

运行结果:

E:\Programs_Way\Python\python.exe D:/Prj/_PythonSelf/Object_oriented_programming/_11method_classification.py
This is a object method! 1 2
<class '__main__.test'>
This is a class method! 1 2
<class '__main__.test'>
This is a class method! 1 2
This is a bind method! 1 2
This is a static method! 1 2
This is a static method! 1 2

Process finished with exit code 0

常用函数

code:_12Commonly_used_functions.py

# ******************************************************
"""
常用函数:
    issubclass(class1,class2)---检测class1是否为class2的子类
    isinstance(对象,类)---检测一个对象是否是指定类的实例化结果,该对象也认为是该类的父类的实例化结果。
    hasattr(类/对象,成员名称字符串)---检测类/对象是否包含指定名称的成员,私有成员无法检测
    getattr(类/对象,成员名称字符串)---获取类/对象的成员,获取不到就报错,私有成员无法获取
    setattr(类/对象,成员名称字符串,设置的新值)---设置类/对象成员的属性值
    delattr(类/对象,成员名称字符串)---删除类/对象的成员属性,和del直接删除对象的成员是一样的结果
        只能删除该类自己声明的成员,不能删除继承的成员,无法删除也不会报错
        只能删除对象自己的成员,无法删除类声明的成员
    dir()---获取对象所有的成员列表
"""


class test:
    name = "Jasmine"
    age = 23

    def func(self):
        print("func()********************")


class test_sub(test):
    __score = 100

    def func1(self):
        print("func1()*******************")


print("issubclass()********************************************")
res = issubclass(test_sub,test)
print(f"issubclass(test_sub,test) = {res}")
obj_test = test_sub()
print("isinstance()********************************************")
res = isinstance(obj_test,test_sub)
print(f"isinstance(obj_test,test_sub) = {res}")
res = isinstance(obj_test,test)
print(f"isinstance(obj_test,test) = {res}")
print("hasattr()********************************************")
res = hasattr(obj_test,'name')
print(f"hasattr(obj_test,'name') = {res}")
res = hasattr(obj_test,'score')
print(f"hasattr(obj_test,'score') = {res}")
res = hasattr(test_sub,'name')
print(f"hasattr(test_sub,'name') = {res}")
res = hasattr(test_sub,'score')
print(f"hasattr(test_sub,'score') = {res}")
print("getattr()********************************************")
res = getattr(obj_test,'name')
print(f"getattr(obj_test,'name') = {res}")
# res = getattr(obj_test,'score')  # 会报错
# print(f"getattr(obj_test,'score') = {res}")
res = getattr(test_sub,'name')
print(f"getattr(test_sub,'name') = {res}")
# res = getattr(test_sub,'score')  # 会报错
# print(f"getattr(test_sub,'score') = {res}")
print("setattr()********************************************")
setattr(obj_test,'name','lili')
print(f"obj_test.name = {obj_test.name}")
setattr(obj_test,'score',99)
print(f"obj_test.score = {obj_test.score}")  # 可以修改成功,但是不建议这样做
setattr(test_sub,'name','lili')
print(f"test_sub.name = {test_sub.name}")
setattr(test_sub,'score',99)
print(f"test_sub.score = {test_sub.score}")  # 可以修改成功,但是不建议这样做
setattr(test,'score',99)  # 没有这个成员的话就给添加一个嘿嘿
print(f"test.score = {test.score}")  # 可以修改成功,但是不建议这样做
print("delattr()********************************************")
delattr(test,'score')
delattr(test_sub,'name')  # 无法删除但是也不会报错
print(f"test_sub.name = {test_sub.name}")
delattr(obj_test,'score')  # 无法删除但是也不会报错
print(f"obj_test.score = {obj_test.score}")
delattr(test_sub,'score')  # 无法删除但是也不会报错
# print(f"test_sub.score = {test_sub.score}")  # 删除了就不能访问了
print("dir()********************************************")
print(f"dir(obj_test) = {dir(obj_test)}")

运行结果:

E:\Programs_Way\Python\python.exe D:/Prj/_PythonSelf/Object_oriented_programming/_12Commonly_used_functions.py
issubclass()********************************************
issubclass(test_sub,test) = True
isinstance()********************************************
isinstance(obj_test,test_sub) = True
isinstance(obj_test,test) = True
hasattr()********************************************
hasattr(obj_test,'name') = True
hasattr(obj_test,'score') = False
hasattr(test_sub,'name') = True
hasattr(test_sub,'score') = False
getattr()********************************************
getattr(obj_test,'name') = Jasmine
getattr(test_sub,'name') = Jasmine
setattr()********************************************
obj_test.name = lili
obj_test.score = 99
test_sub.name = lili
test_sub.score = 99
test.score = 99
delattr()********************************************
test_sub.name = Jasmine
obj_test.score = 99
dir()********************************************
dir(obj_test) = ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_test_sub__score', 'age', 'func', 'func1', 'name']

Process finished with exit code 0

魔术方法

__init__
__new__
__call__
__len__
__str__
str()和repr()函数
__repr__
repr()函数
__bool__
__del__

code:_13Magic_methods.py

# *****************************************
"""
魔术方法:是类中的成员方法,不需要手动调用,在某种情况下会自动触发
    特点:多数的魔术方法,前后都有两个下划线
        魔术方法不是自己定义的,是系统定义好的,我们使用。
    __init__初始化方法---相当于C++的构造函数
        触发机制:实例化对象时,自动触发的方法。
        作用:可以在对象实例化后完成对象的初始化---属性的赋值,方法的调用,打开或创建一些资源。。
        参数:self,其他参数根据需求进行定义即可
        应用场景:文件的打开,数据的获取
        返回值:无
        注意事项:无
    __new__构造方法:
        触发机制:实例化对象时自动触发(__init__之前)
        作用:管理控制对象创建的过程
        参数:cls,其他参数根据初始化方法的参数进行决定
        返回值:必须返回object.__new__(cls)进行对象的创建,如果没有返回值,则实例化对象的结果为None
        注意事项:
            1.__new__方法的参数和__init__方法的参数要保持一致,除了第一个参数
            2.必须返回object.__new__(cls)进行对象的创建,如果没有返回值,则实例化对象的结果为None
    __call__
        触发机制:把对象当作函数直接调用时自动触发
        作用:一般用于归纳类和对象的操作步骤,方便调用
        参数:self,其他参数根据调用需求确定
        返回值:可有可无
    __len__:
        触发机制:使用len(对象),设置返回的值,此时自动触发
        作用:可以使用len函数检测当前对象中的某个数据信息
        参数:self
        返回值:必须有,而且必须是一个整型
        注意事项:len要获取什么属性的值,就在返回值中返回哪个属性的长度
    __str__:
        触发机制:使用str(对象),print(对象)时,设置返回/显示的字符串,此时自动触发
        作用:可以返回/打印当前类的信息
        参数:self
        返回值:必须有,而且必须是字符串
        注意事项:如果类没有定义__str__()和__repr__()的话,默认返回<__main__.Person object at 0x000001F3A9E0BFA0>
        如果类没有定义__str__()而定义了__repr__()的话,返回__repr__()返回的字符串
        如果类定义了__str__()和__repr__()的话,返回__str__()返回的字符串
    str()和repr()函数:
        str和repr函数都能够把其他类型的数据转换为字符串
        str函数会把对象转换为更适合人类阅读的形式
        repr函数会把独享转换为解释器读取的形式
        如果数据对象并没有明显的区别,str和repr返回的结果是一样的
    __repr__:
        触发机制:使用repr(对象)时,自动触发
        作用:可以返回当前类的信息
        参数:self
        返回值:必须有,而且必须是字符串
        注意事项:正常情况下,如果没有__str__魔术方法,__repr__方法就会代替__str__方法
        如果类没有定义__str__()和__repr__()的话,默认返回<__main__.Person object at 0x000001F3A9E0BFA0>
        如果类没有定义__str__()而定义了__repr__()的话,返回__repr__()返回的字符串
        如果类定义了__str__()和__repr__()的话,返回__str__()返回的字符串
    repr()函数:
        如果没有定义__repr__(),使用repr()函数,返回默认的字符串<__main__.Person object at 0x000001F3A9E0BFA0>
        如果定义了__repr__(),使用repr()函数,返回__repr__()返回的字符串
    __bool__:
        触发机制:使用bool(对象)时,自动触发;默认情况下会返回True
        作用:可以代替bool(对象)中的‘对象’为对象中的属性,返回bool类型
        参数:self
        返回值:必须是bool类型
    __del__析构方法:
        触发机制:当前类实例化的对象被销毁时,自动触发
        作用:关闭一些打开的资源,比如关闭初始化方法中打开的文件
        参数:self
        返回值:无
        注意事项:无
        注意:是对象被销毁时触发了这个方法,而不是这个方法销毁了对象
"""


class Person:
    name = ''
    age = 0
    sex = '女'

    def __new__(cls,n,a,s):
        print("构造函数被调用啦!")
        return object.__new__(cls)

    def __init__(self,n,a,s):
        print("初始化函数被调用啦!")
        self.name = n
        self.age = a
        self.sex = s

    def __call__(self,):
        print("call函数被调用啦!")

    def __len__(self):
        return len(self.name)

    def __str__(self):
        return "str__这是Person类的一个实例~"

    def __repr__(self):
        return "repr__这是Person类的一个实例~"

    def __bool__(self):
        return bool(self.name)

    def __del__(self):
        print("析构函数被调用啦!")


Jasmine = Person('Jasmine',23,'女')
Jasmine()
# 如果类没有定义__str__()和__repr__()的话,默认返回<__main__.Person object at 0x000001F3A9E0BFA0>
# 如果类没有定义__str__()而定义了__repr__()的话,返回__repr__()返回的字符串
# 如果类定义了__str__()和__repr__()的话,返回__str__()返回的字符串
print(f"Jasmine = {Jasmine}")
# 返回了当前对象name的长度
print(f"len(Jasmine) = {len(Jasmine)}")
print(f"bool(Jasmine) = {bool(Jasmine)}")
print(f"repr(Jasmine) = {repr(Jasmine)}")

num = 123
r1 = str(num)
r2 = repr(num)
print(r1,type(r1))
print(r2,type(r2))
str_123 = '123'
r1 = str(str_123)
r2 = repr(str_123)
print(r1,type(r1))
print(r2,type(r2))

运行结果:

E:\Programs_Way\Python\python.exe D:/Prj/_PythonSelf/Object_oriented_programming/_13Magic_methods.py
构造函数被调用啦!
初始化函数被调用啦!
call函数被调用啦!
Jasmine = str__这是Person类的一个实例~
len(Jasmine) = 7
bool(Jasmine) = True
repr(Jasmine) = repr__这是Person类的一个实例~
123 <class 'str'>
123 <class 'str'>
123 <class 'str'>
'123' <class 'str'>
析构函数被调用啦!

Process finished with exit code 0

成员魔术方法

code:_14Magic_method_members_relevant.py

# *********************************************************
"""
成员相关魔术方法:
    __getattribute__:优先级最高
        触发机制:当访问对象成员时,自动触发,无论当前成员是否存在
        作用:可以在获取对象成员时,对数据进行一些处理
        参数:self,item接收当前访问的成员名称
        返回值:可有可无,返回的值就是访问的结果
        注意事项:在当前的魔术方法中,禁止对当前对象的成员进行访问,会导致递归(递归多次后报错)
            如果一定需要的话,必须使用 object.__getattribute__()来进行访问
            格式:object.__getattribute__(self,item)
    __getattr__:
        触发机制:访问对象中不存在的成员时,自动触发
        作用:防止访问不存在的成员时报错,也可以为不存在的成员进行创建和赋值操作
        参数:self,item接收当前访问的成员名称
        返回值:成员不存在时返回None
        注意事项:当存在__getattribute__时,将会去执行__getattribute__方法
            __getattr__由于优先级较__getattribute__低,类似于被隐藏了
    __setattr__:
        触发机制:当给对象的成员进行赋值操作时会自动触发(包括添加,修改)
        作用:可以限制或管理对象成员的添加和修改操作,成员不存在时自动添加成员
        参数:self,key设置的成员名,value设置的成员值
        返回值:无
        注意事项:在当前的魔术方法中禁止给当前的成员进行直接赋值操作,会导致递归
            如果想要给当前独享的成员进行赋值,必须使用object.__getattr__()
            格式:object.__getattr__(self,key,value)
            如果本方法中没有给对象成员赋值,那么对象成员赋值失败。
    __delattr__:
        触发机制:删除对象成员时触发
        作用:限制对象成员的删除,还可以在删除不存在成员时防止报错
        参数:self,item删除成员的名称
        返回值:无
        注意事项:在当前魔术方法中禁止直接删除对象的成员,会导致递归
            如果想要删除当前对象的成员,必须使用object.__delattr__()来进行访问
            格式:object.__delattr__(self,item)
    访问成员的优先级:如果前面的调用成功,后面的不再执行
        __getattribute__
        数据描述符
        当前对象的成员属性
        当前类的成员属性
        非数据描述符
        父类的成员属性
        __getattr__
"""


class Person:
    name = "name"
    age = "age"
    sex = "sex"

    def sing(self):
        print("唱*******************")

    def dance(self):
        print("跳*******************")

    def __init__(self,n,a,s):
        self.name = n
        self.age = a
        self.sex = s

    def __getattribute__(self, item):
        try:
            res = object.__getattribute__(self, item)
            return res
        except:
            return '成员不存在!'

    def __getattr__(self,item):
        print('成员不存在!')

    def __setattr__(self,key,value):
        object.__setattr__(self,key,value)

    def __delattr__(self,item):
        object.__delattr__(self,item)


Jasmine = Person("Jamsine",'23','女')
print(f"Jamsine.name = {Jasmine.name}")
print(f"Jamsine.hair = {Jasmine.hair}")
Jasmine.name = 'lili'
print(f"Jamsine.name = {Jasmine.name}")
Jasmine.hair = 'black'
print(f"Jamsine.hair = {Jasmine.hair}")
del Jasmine.hair
print(f"Jamsine.hair = {Jasmine.hair}")

运行结果:

E:\Programs_Way\Python\python.exe D:/Prj/_PythonSelf/Object_oriented_programming/_14Magic_method_members_relevant.py
Jamsine.name = Jamsine
Jamsine.hair = 成员不存在!
Jamsine.name = lili
Jamsine.hair = black
Jamsine.hair = 成员不存在!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasmine-Lily

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值