python3基础练习 发表于 2019-05-07 最近业务上在写一个基于串口的python-sdk 写下来真觉得python是个好东西,简单、强大、生态好! 当然了,也有许多要注意的。 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182class Hello(): name = 'dottie' def __init__(self): self._age = 11 @property def age(self): print('get', self._age) return self._age # 可以进行参数校验 # 该方法内不能调用self.age = xxx 会导致递归 @age.setter def age(self, age): print('set', age) if age < 10: raise ValueError('值不能小于10') self._age = age + 1 def set_name(self, name): self.name = name # 类方法比静态方法就是多了一个默认参数, # 类似 实例方法第一个参数是self @classmethod def hello(cls): '''cls为该类''' print('classmethod', cls.name) @staticmethod def world(): print('staticmethod', Hello.name) # 私有实例方法 def _hey(self): print('>>> hello {}'.format('guys')) print(f'hello{"guy"}') return 'hey guys!' Hello.name = 'daejong'hello = Hello()# 类属性可以用类名和self访问。# 但是只能通过类名调用类属性来修改类属性值# 通过self调用类属性只能访问类属性(只读)print(hello.name) # daejong 这里访问的是类属性print(Hello.name) # daejong 这里访问的是类属性hello.set_name('china')print(hello.name) # china 这里访问的实例属性nameprint(Hello.name) # daejong 这里访问的是类属性print(hello.age) # 11hello.age = 22print(hello.age) # 22hello.hello() # classmethod daejongHello.hello() # classmethod daejonghello.world() # staticmethod daejongHello.world() # staticmethod daejongclass Child(Hello): passprint(Child.name)Child.hello() # classmethod daejongChild.world() # staticmethod daejongchild = Child()child.hello() # classmethod daejongchild.world() # staticmethod daejongprint(child.name) # daejongprint(child.age) # 11