python面向对象3

一些思考与学习

  1. 属性保护:通过设置双前下划线来设置保护,保护起来之后就不可以直接访问了。(但是在可以修改,只是不可以访问;对于继承这个类的新类则不能修改其中的保护内容)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Test:
def __init__(self, foo):
self.__foo = foo

def __bar(self):
print(self.__foo)
print('__bar')


def main():
test = Test('hello')
test.__bar()
# AttributeError: 'Test' object has no attribute '__bar'
print(test.__foo)
# AttributeError: 'Test' object has no attribute '__foo'


if __name__ == "__main__":
main()
  1. 在定义类的时候要注意对应的函数是否有返回值,没有返回值意为修改了但是不告诉你。
1
2
3
4
5
6
def move_to(self):
a = int(input("position of x:\n"))
b = int(input("position of y:\n"))
self.x = a
self.y = b
print(f"the current position of the point is ({a}, {b})")

如这里偷偷改了“点”这个属性的x和y,但是没有明示出来。

  1. 关于@property。比如我有一个Person类,name属性,外部可以把name属性设定为任意的东西。为了对外部设置加以限制,如不能带有数字这样的要求,我们可以把name属性改为__name禁止从外界直接访问。然后通过创造其他函数来对name进行修改。为了进一步简化,将新的函数直接命名为name,然后进行操作,这样需要在函数前用@property,就可以将name这个方法(函数)直接当成属性来使用。property包含getter和setter两种方法,在定义函数的时候不会名字重复。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Person(object):

def __init__(self, name, age):
self._name = name
self._age = age

# 访问器 - getter方法
@property
def name(self):
return self._name

# 访问器 - getter方法
@property
def age(self):
return self._age

# 修改器 - setter方法
@age.setter
def age(self, age):
self._age = age

def play(self):
if self._age <= 16:
print('%s正在玩飞行棋.' % self._name)
else:
print('%s正在玩斗地主.' % self._name)


def main():
person = Person('王大锤', 12)
person.play()
person.age = 22
person.play()
# person.name = '白元芳' # AttributeError: can't set attribute


if __name__ == '__main__':
main()
  1. 限定Person对象只能绑定_name, _age和_gender属性
1
__slots__ = ('_name', '_age', '_gender')
  1. 类的方法分类:
    对象方法:给对象发送消息,实例属性属于具体对象,比如gty是person类,gty这个实例的身高体重等性质都是用对象方法创建和修改
    静态方法:让类里的方法直接被类调用,就像正常调用函数一样,无参数
    类方法:类方法一般和类属性配合使用。类方法必须有一个cls参数表示这个类,可以直接用类名去调用,可以与类属性交互(类属性就是属于这个类的性质,比如person类都有两个眼睛四条腿)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Person(object):
eyes = 2
legs = 2
toes = 10

def __init__(self, name):
self.name = name

@classmethod
def get_inform(cls): # 主要用于类属性的处理
print("eyes:", cls.eyes)
print("toes:", cls.toes)

@staticmethod
def is_good_name(name): # 把函数当作正常函数来使用
if len(name) > 3:
print("not a good name")
else:
print("good name")


p1 = Person('gty')
Person.get_inform()
p1.is_good_name('gty')

### output:
eyes: 2
toes: 10
good name
查看评论