2/100

定义类

python使用关键字class来定义类,在类名后的括号里写父类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Student(object):

# 相当于Java的构造体,类的field可以直接赋值,不用事先定义
def __init__(self, name, age):
self.name = name
self.age = age

# 参数self相当于Java中的this,在调用方法的时候不需要指定,单如果没有这个参数就无法使用类的field
def study(self, course):
print(f'studing: {course}')

def watch_movie(self):
if self.age < 18:
print('%s只能观看《熊出没》.' % self.name)
else:
# 这是原作者 [jackfrued] 的爱好
print('%s正在观看岛国爱情大电影.' % self.name)

可见性

python并没有复杂而严格的可见性设置,虽然可以通过在方法和变量前加两个下划线来设置私有性,但这其实只是改变了访问规则而已。

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
class Test:

def __init__(self, foo):
self.__foo = foo

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


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

# 在前面添加 _Test 就可以访问了
test._Test__bar()
print(test._Test__foo)


if __name__ == "__main__":
main()

一般使用单下划线来表明方法或变量是受保护的,但这也只是一种隐含的意思而已。

@property装饰器
可以使用@property来包装属性,这样属性将会被封装起来,使用@property装饰的方法可以作为getter来使用,想要使用setter则需要@xxx.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
39
40
41
class Person(object):

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

# 如果没有这个修饰,下面的person.name = 'Bob' 就不会报错
@property
def name(self):
return self._name


@property
def age(self):
return self._age


@age.setter
def age(self, age):
self._age = age


def play(self):
if self.age <= 16:
print('plage game')
else
print('work')


def main():
person = Person('Alcie', 12)
person.play()
person.age = 22
person.play()
# AttributeError: can't set attribute
person.name = 'Bob'


if __name__ == '__main__':
main()