类的成员

类的内置成员

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)@classmethoddef 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)@staticmethoddef 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 2Process 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 = 23def func(self):print("func()********************")class test_sub(test):__score = 100def 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 = 0sex = '女'def __new__(cls,n,a,s):print("构造函数被调用啦!")return object.__new__(cls)def __init__(self,n,a,s):print("初始化函数被调用啦!")self.name = nself.age = aself.sex = sdef __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 = nself.age = aself.sex = sdef __getattribute__(self, item):try:res = object.__getattribute__(self, item)return resexcept: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

Python类的成员相关推荐

  1. python类中成员的的调用

    python类中成员的调用 python类中的方法到底到底是方法还是函数取绝于调用者, 当类名调用这个方法时他是一个函数 class Foo(object):def f1(self):print(&q ...

  2. python类的成员函数_Python实现动态添加类的属性或成员函数的解决方法

    某些时候我们需要让类动态的添加属性或方法,比如我们在做插件时就可以采用这种方法.用一个配置文件指定需要加载的模块,可以根据业务扩展任意加入需要的模块. 本文就此简述了Python实现动态添加类的属性或 ...

  3. [转载] python类内部成员的访问及外部访问(入门)

    参考链接: 在Python中更改类成员 class Student(): school = "xcxy"                    # 类属性 __major = &q ...

  4. python类的成员没有访问控制限制_Python 访问限制 private public的详细介绍

    一.知识点 在一个模块中,我们可能会定义很多函数和变量.但有的函数和变量我们希望能给别人使用,有的函数和变量我们希望仅仅在模块内部使用,so? 我们可以通过定义该函数.变量是公开的还是私有的来达到该目 ...

  5. python类的成员函数_python特殊成员函数

    1.__init__():构造函数 2.__del__():析构函数 3.print(__doc__):打印描述信息 4.print(Dog.__module__):类来自的模块 5.print(d1 ...

  6. python类的成员函数_注入一个python类成员函数

    你在这里要做的是Child2.foo用self不是a的方法调用未绑定的方法Child2. 这是非法的,Python 2将检测到并提出一个TypeError解释错误的地方:TypeError: unbo ...

  7. python类的成员函数_Python为类对象动态添加成员函数

    Python: 为对象动态添加函数 , 且函数定义 来自一个 str 在 Python 中 , 通常情况下 , 你只能为对象添加一个已经写好的方法 需求 : 传入一个 str 类型的变量 , 其值是一 ...

  8. python中的类的成员变量以及property函数

    1 python类的各种变量 1.1 全局变量 在类外定义的变量. 1.2 类变量 定义在类里面,所有的函数外面的变量.这个变量只有一份,是所有的对象共有的.在类外用"类."来引用 ...

  9. 用电脑回收站的数据保护机制:理解python类成员保护和访问限制,及编程思想

    类成员保护和访问限制有什么用 python类的成员可以通过"成员保护和访问限制的机制"非常大程度地禁止类实例对象对其进行直接访问和直接的修改,只能通过类实例方法来获取.访问或修改. ...

最新文章

  1. mysql 分页测试,
  2. 360Apm源码解析
  3. 图解设计模式(1) Iterator 模式
  4. Jquery 点击当前的标签对象获取值 与JS整理
  5. PVFS2 1.4.0的安装、配置与性能测试
  6. 使用Struts2 验证框架,验证信息重复多次出现
  7. java 监测文件夹_实时监测文件夹中新增的文件和文件夹(java)
  8. AI架构师:深度学习框架、部署上线及应用,一文梳理
  9. Fences报错,explorer.exe未正确关闭问题
  10. 关于程序组团队建设的几点想法
  11. k8s出现问题导致cpu使用率过高
  12. QT中主线程终止子线程中的死循环
  13. 完整数字华容道05:游戏结束
  14. 决策树与随机森林初探
  15. JDK动态代理源码解析
  16. 华为云服务治理 | 隔离仓的作用
  17. 新加坡环球影城:新加坡亲子游一日游好去处
  18. cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies
  19. 2022.11.20 学习周报
  20. Excel中提取url的文件名

热门文章

  1. Dockder的CS模式:
  2. 【C/S】FIPS安全验证问题
  3. 如何在 Ubuntu 和 CentOS 上启用 Nginx 的 HTTP/2 协议支持
  4. 2015生命之旅---第二站长沙杭州
  5. linux bash 获取 国内常见网站的IP列表
  6. 使用Java 8 Lambda表达式对Employee类进行操作
  7. pdf转换成word教程
  8. ASP.NET页面之间传值Session(2)
  9. Function spec
  10. Ubuntu 安装 Eclipse C/C++开发环境