一, 属性 (特性)
普通方法去执行的时候, 后面需要加括号, 特性方法执行的时候和静态字段一样不需要不需要加括号.
特性方法不和字段同名.
特性方法不能传参数.
获取特性
- class Foo:
- def __init__(self,name):
- self.name = name
- # 普通方法
- def start(self):
- temp = '%s sb' %self.name
- return temp
- # 特性, 将方法的执行方式变为和字段一样
- @property
- def end(self):
- temp = '%s gd'%self.name
- return temp
- obj = Foo('alexsel')
- ret1 = obj.start()
- ret2 = obj.end
- print(ret2)
- print(obj.name)
输出结果:
- alexsel gd
- alexsel
设置特性
设置特性方法的时候, 所需要加的装饰器名字规则是, 你所设置特性方法名字点 setter(例如:@end.setter)
- class Foo:
- def __init__(self,name):
- self.name = name
- # 普通方法
- def start(self):
- temp = '%s sb' %self.name
- return temp
- # 特性, 将方法的执行方式变为和字段一样
- @property
- def end(self):
- temp = '%s gd'%self.name
- return temp
- # 如果需要使用设置特性的的方法, 就需要这个点前面名字和所要设置特性的方法同名, 就像这里的 end
- @end.setter
- def end(self,value):
- print(value)
- self.name = value
- obj = Foo('alexsel')
- # 获取特性, 获取特性的时候, 拿到的是 @Property 的返回值
- ret2 = obj.end
- print(ret2)
- # 设置特性, 设置特性的时候, 会执行 @end.setter 下面的方法, 这个'aaa'就传递给 value
- obj.end = 'aaa'
- ret1 = obj.end
- print(ret1)
输出结果:
- alexsel gd
- aaa
- aaa gd
这个特性在 python 中不是特别常用, 因为我们一般可以使用普通的方法代替特性方法.
二, 成员修饰符
首先介绍'__', 这个在命名之前添加就会变成私有的, 只有在类的内部才能访问.
- class Foo:
- book = 'alexsel'
- #命名的时候前面添加__, 只有在类的内部才能访问, 在外部无法访问
- __book = 'book'
- def __init__(self):
- self.__name = 'alexsel'
- def start(self):
- print(Foo.__book)
- print(self.__name)
- def __end(self):
- print('__end')
- obj = Foo()
- print(obj.book)
- # print(obj.__book) #这种无法拿到字段
- # 在外部也无法调用类私有方法
- #obj.__end()
- # 通过内部方法调用拿到字段
- obj.start()
输出结果:
- alexsel
- book
- alexsel
私有的属性只有自己可以访问, 当某个类继承这个类之后, 也无法访问父类的私有属性.
- class Foo:
- book = 'alexsel'
- __book = 'book'
- def __init__(self):
- self.__name = 'alexsel'
- def start(self):
- print(Foo.__book)
- print(self.__name)
- self.__end()
- def __end(self):
- print('__end')
- class Bar(Foo):
- def start(self):
- print(self.__name)# 子类继承父类, 也无法调用父类的私有属性
- obj = Bar()
- obj.start()
输出结果:
报错
静态方法也是如此
- class Foo:
- book = 'alexsel'
- __book = 'book'
- def __init__(self):
- self.__name = 'alexsel'
- def start(self):
- Foo.__add() #内部调用私有静态方法
- def __end(self):
- print('__end')
- @staticmethod
- def __add():
- print('add')
- obj = Foo()
- obj.start()
输出结果:
add
python 成员修饰符有两种, 一种是共有的, 一种是私有的, 共有的都可以访问, 私有的只有自己可以访问, 或者在外部间接访问.
但是还有一种强行访问私有属性的方法, 如下:
- class Foo:
- book = 'alexsel'
- __book = 'book'
- def __init__(self):
- self.__name = 'alexsel'
- def start(self):
- Foo.__add() #内部调用私有静态方法
- def __end(self):
- print('__end')
- @staticmethod
- def __add():
- print('add')
- obj = Foo()
- print(obj._Foo__book)
输出结果:
book
虽然可以使用, 但是不推荐这种使用方法.
来源: https://www.cnblogs.com/liudi2017/p/9380280.html