1.对象的定义和成员变量
#!/usr/bin/python3
# classes.py by Bill Weinman [http://bw.org/]# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
class Duck:
def __init__(self,value=12):
print('constructor')
self._v=value
def quack(self):
print('Quaaack!',self._v)
def walk(self):
print('Walks like a duck.',self._v)
def main():
donald = Duck()
donald.quack()
donald.walk()
fork = Duck(23)
fork.quack()
fork.walk()
if __name__ == "__main__": main()
2 dictionary to handle variable
2.1 no dictionary
#!/usr/bin/python3
# classes.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
class Duck:
def __init__(self,color,feet):
print('constructor')
self._color=color
self._feet=feet
def quack(self):
print('Quaaack!',self._v)
def walk(self):
print('Walks like a duck.',self._v)
def get_color(self):
return self._color
def set_color(self,color):
self._color=color
def get_feet(self):
return self._feet
def set_feet(self,feet):
self._color=feet
def main():
donald = Duck('white',2)
print(donald.get_color())
print(donald.get_feet())
if __name__ == "__main__": main()
constructor
white
2
如果我们用dictionary 来处理成员变量 将会轻松许多
#!/usr/bin/python3
# classes.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
class Duck:
def __init__(self,**kwargs):
print('constructor')
self.variables=kwargs
def quack(self):
print('Quaaack!',self._v)
def walk(self):
print('Walks like a duck.',self._v)
def set_variable(self,k,v):
self.variables[k]=v
def get_variable(self,k):
return self.variables.get(k,None)
def main():
donald = Duck(color='white',feet=2)
print(donald.get_variable('color'))
print(donald.get_variable('feet'))
if __name__ == "__main__": main()
constructor
white
2