python入门第二十四天----成员修饰符 类的特殊成员

Posted 独孤_败天

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python入门第二十四天----成员修饰符 类的特殊成员相关的知识,希望对你有一定的参考价值。

1 #成员修饰符  修饰符可以规定内部的字段、属性、方法等 是共有的成员,私有的成员
2 class Foo:
3     def __init__(self,name,age):
4         self.name=name
5         self.age=age  #可以在外部直接访问
6 
7 obj=Foo(\'Jack\',22)
8 print(obj.name)
9 print(obj.age)
共有字段

1 #成员修饰符  修饰符可以规定内部的字段、属性、方法等 是共有的成员,私有的成员
2 class Foo:
3     def __init__(self,name,age):
4         self.name=name
5         #self.age=age  #可以在外部直接访问
6         self.__age=age #添加 __ 两个下划线,就变成私有字段,外部不能访问
7 obj=Foo(\'Jack\',22)
8 print(obj.name)
9 print(obj.age)

运行结果:

"D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
Traceback (most recent call last):
Jack
  File "F:/python从入门到放弃/7.24/面向对象.py", line 16, in <module>
    print(obj.age)
AttributeError: \'Foo\' object has no attribute \'age\'

Process finished with exit code 1

私有字段外部不能直接访问。可以通过内部的方法,间接访问

 1 #成员修饰符  修饰符可以规定内部的字段、属性、方法等 是共有的成员,私有的成员
 2 class Foo:
 3     def __init__(self,name,age):
 4         self.name=name
 5         #self.age=age  #可以在外部直接访问
 6         self.__age=age #添加 __ 两个下划线,就变成私有字段,外部不能访问
 7     def get_age(self):
 8         return self.__age
 9 obj=Foo(\'Jack\',22)
10 print(obj.name)
11 print(obj.get_age())

运行结果:

"D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
Jack
22

Process finished with exit code 0
 1 #成员修饰符  修饰符可以规定内部的字段、属性、方法等 是共有的成员,私有的成员
 2 class Foo:
 3     gender=\'\' #对于静态字段
 4     def __init__(self,name,age):
 5         self.name=name
 6         #self.age=age  #对于普通字段可以在外部直接访问
 7         self.__age=age #添加 __ 两个下划线,就变成私有字段,外部不能访问
 8     def get_age(self):
 9         return self.__age
10 obj=Foo(\'Jack\',22)
11 # print(obj.name)
12 # print(obj.get_age())
13 print(obj.gender)
静态字段
 1 class Foo:
 2     #gender=\'男\' #对于静态字段
 3     __gender = \'\'
 4     def __init__(self,name,age):
 5         self.name=name
 6         #self.age=age  #对于普通字段可以在外部直接访问
 7         self.__age=age #添加 __ 两个下划线,就变成私有字段,外部不能访问
 8     def get_age(self):
 9         return self.__age
10     def get_gender(self):
11         return Foo.__gender
12 obj=Foo(\'Jack\',22)
13 # print(obj.name)
14 # print(obj.get_age())
15 print(obj.get_gender())
私有静态字段
 1 class Foo:
 2     __gender=\'\'
 3     def __init__(self):
 4         pass
 5 
 6     # def get_gender(self):
 7     #     return Foo.__gender
 8 
 9     @staticmethod
10     def get_gender():
11         return Foo.__gender
12 # obj=Foo()
13 # print(obj.get_gender())
14 print(Foo.get_gender())
通过静态方法,访问私有字段

 

 

 1 #案例 数据库账户
 2 class Database:
 3     __root="root"
 4     __pwd=\'abc123\'
 5     __port=\'3306\'
 6     __dbname=\'ssoa\'
 7     # def __init__(self,pwd):
 8     #     pass
 9 ###############只读模式########################
10     def get_root(self): #只能访问,不能修改  可读
11         return self.__root
12     def get_port(self):
13         return self.__port
14     
15     ###########读写模式 #################
16     def get_pwd(self):  #获取密码
17         return self.__pwd
18     def set_pwd(self,pwd):  #修改密码
19         self.__pwd = pwd
20 
21 db=  Database()
22 print(db.get_pwd()) #调用密码
23 db.set_pwd(\'456\')   #修改密码
24 print(db.get_pwd())#调用密码
读写 只读

 

 1 class ClassFather:
 2     def __init__(self):
 3         self.__age=23
 4         self.score=90
 5 
 6 class ClassSon(ClassFather):
 7     def __init__(self,name):
 8         self.name=name
 9         self.__gender=\'\'
10         super().__init__()
11 
12     def show(self):
13         print(self.name)
14         print(self.__gender)
15         print(self.score)
16         #print(self.__age)#私有字段只能在类的内部使用,不能被继承
17 
18 s=ClassSon(\'李逵\')
19 s.show()
私有字段只能在类的内部使用,不能被继承



类的特殊成员

 __init__/__call__

 1 class Foo:
 2     def __init__(self): #对象后面加上() 自动执行 init 方法
 3         print(\'init\')
 4 
 5 
 6     def __call__(self, *args, **kwargs):  ##对象后面加() 自动执行 call 方法
 7         print(\'call\')
 8 
 9 
10 obj=Foo()
11 obj()
##相当于 Foo()()

__int__/__str__

 1 class Foo:
 2     def __init__(self):
 3         pass
 4     def __int__(self):
 5         return 111
 6     def __str__(self):
 7         return \'string\'
 8 obj=Foo()
 9 
10 print(obj,\'\\n\',type(obj))
11 
12 #int ,对象,自动执行对象的__int__ 方法,并将返回值赋值给int对象
13 r=int(obj)
14 print(r)
15 #str ,对象,自动执行对象的__str__ 方法,并将返回值赋值给str对象
16 t=str(obj)
17 print(t)

运行结果:

"D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
string 
 <class \'__main__.Foo\'>
111
string

Process finished with exit code 0

在实际使用中,使用__str__() 方法的频率更大

例如:

1 class Foo:
2     def __init__(self,name,age):
3         self.name=name
4         self.age=age
5 
6 obj=Foo(\'Jach\',12)
7 print(obj)

运行结果:

"D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
<__main__.Foo object at 0x000000000222D1D0>

Process finished with exit code 0

 1 class Foo:
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.age=age
 5 
 6     def __str__(self): #用于打印
 7         return \'%s----%s\'%(self.name,self.age)
 8 
 9 obj=Foo(\'Jach\',12)
10 #如果直接调用对象打印出来,会默认直接调用 __str__ 方法
11 #内部先把\'print(obj)\'默认转换成>>>\'print(str(obj))\' 获取其返回值 
12 print(obj)

运行结果:

"D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
Jach----12

Process finished with exit code 0

__add__

 1 class Foo:
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.age=age
 5 
 6     def __add__(self, other):
 7         #self == obj(\'亚瑟\',12)
 8         #other==obj(\'后羿\',23)
 9         # return self.age+other.age
10         return Foo(self.name,other.age)
11 
12 obj=Foo(\'亚瑟\',12)
13 obj2=Foo(\'后羿\',23)
14 
15 r=obj+obj2
16 #两个相加时,会自动执行第一个对象的 __add__ 方法,并且把第二个参数当做参数传递进去
17 print(r,type(r))
18 print(r.name)
19 print(r.age)

运行结果:

"D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
<__main__.Foo object at 0x00000000024BD4E0> <class \'__main__.Foo\'>
亚瑟
23

Process finished with exit code 0

构造方法 对象被创造的时候自动触发  __init__

析构方法 对象被销毁的时候自动触发  __del__ 

 1 class Foo:
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.age=age
 5 
 6     def __add__(self, other):
 7         #self == obj(\'亚瑟\',12)
 8         #other==obj(\'后羿\',23)
 9         # return self.age+other.age
10         return Foo(self.name,other.age)
11     def __del__(self):
12         print(\'析构方法,对象销毁时,自动执行\')
13 
14 obj=Foo(\'亚瑟\',12)
15 obj2=Foo(\'后羿\',23)
16 
17 r=obj+obj2
18 #两个相加时,会自动执行第一个对象的 __add__ 方法,并且把第二个参数当做参数传递进去
19 print(r,type(r))
20 print(r.name)
21 print(r.age)

运行结果:

"D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
<__main__.Foo object at 0x0000000001EAD470> <class \'__main__.Foo\'>
亚瑟
23
析构方法,对象销毁时,自动执行
析构方法,对象销毁时,自动执行
析构方法,对象销毁时,自动执行

Process finished with exit code 0

__dict__  #将对象中分装的所有成员,通过字典的形式,返回

 1 class Foo:
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.age=age
 5 
 6     def __add__(self, other):
 7         #self == obj(\'亚瑟\',12)
 8         #other==obj(\'后羿\',23)
 9         # return self.age+other.age
10         return Foo(self.name,other.age)
11     def __del__(self):
12         print(\'析构方法,对象销毁时,自动执行\')
13 
14 
15 obj=Foo(\'亚瑟\',12)
16 d=obj.__dict__
17 print(d)

运行结果:

"D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
{\'name\': \'亚瑟\', \'age\': 12}
析构方法,对象销毁时,自动执行

Process finished with exit code 0

__doc__ 文档说明 表示类的描述信息

 

 

class Foo:
    """ 描述类信息,这是用于看片的神奇 """

    def func(self):
        pass

print Foo.__doc__
#输出:类的描述信息
__doc__ 1

 

 1 class Foo:
 2     \'\'\'
 3     当前的简要说明,参数设置等信息
 4     \'\'\'
 5     def __init__(self,name,age):
 6         self.name=name
 7         self.age=age
 8 
 9     def __add__(self, other):
10         #self == obj(\'亚瑟\',12)
11         #other==obj(\'后羿\',23)
12         # return self.age+other.age
13         return Foo(self.name,other.age)
14     def __del__(self):
15         print(\'析构方法,对象销毁时,自动执行\')
16 
17 # obj=Foo(\'亚瑟\',12)
18 # d=obj.__dict__
19 # print(d)
20 print(Foo.__dict__)
__doc__
1 "D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
2 {\'__module__\': \'__main__\', \'__doc__\': \'\\n    当前的简要说明,参数设置等信息\\n    \', \'__init__\': <function Foo.__init__ at 0x00000000021FD2F0>, \'__add__\': <function Foo.__add__ at 0x00000000021FD378>, \'__del__\': <function Foo.__del__ at 0x00000000021FD400>, \'__dict__\': <attribute \'__dict__\' of \'Foo\' objects>, \'__weakref__\': <attribute \'__weakref__\' of \'Foo\' objects>}
3 
4 Process finished with exit code 0
运行结果

__getitem__/__setitem__/__delitem__

 

 1 class Foo:
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.age=age
 5     def __getitem__(self, item):
 6         return item+10
 7     def __setitem__(self, key, value):
 8         print(key,value)
 9     def __delitem__(self, key):
10         print(key)
11 
12 obj=Foo(\'亚瑟\',12)
13 r=obj[8]#在对象后面后加上[] 以索引的方式访问,会自动执行  __getitem__方法
14 print(r)
15 
16 obj[50]=\'得得得得得得\'#通过索引赋值的访问,会自动执行  __setitem__ 方法
17 
18 del obj[50]

运行结果:

"D:\\Program Files (x86)\\python36\\python.exe" F:/python从入门到放弃/7.24/面向对象.py
18
50 得得得得得得
50

Process finished with exit code 0

 

slice 切片类型的内部方法:

class slice(object):
    
   #............ 
   
    start = property(lambda self: 0)
    """:type: int"""

    step = property(lambda self: 0)
    """:type: int"""

    stop = property(lambda self: 0)
    """:type: int"""


    __hash__ = None

__getitem__切片或是索引

 1 class Foo:
 2     def __init__(self,name,age):
 3         self.name=name
 4         self.age=age
 5     def __getitem__(self, item):
 6         print(item,type(item))
 7         # return item+10
 8         if type(item)==slice:
 9             print(\'切片处理\')
10             print(item.start)
11             print(item.step)
12             print(item.stop)
13         else:
14             
15             print("索引处理")
以上是关于python入门第二十四天----成员修饰符  类的特殊成员的主要内容,如果未能解决你的问题,请参考以下文章

Python 入门第四天

Spring入门第二十四课

python入门第三十四天--事件驱动模型

大数据入门第二十四天——SparkStreaming与flumekafka整合

python中类成员修饰符

C#编程(二十四)----------修饰符