stuff={"name":"jack","age":"18","height":"180"}
stuff["city"]="beijing"
print(stuff)
del stuff["city"]
print(stuff)
class mystuff():
# 对象初始化
def __init__(self):
self.tangerine = "hhhhhhhhhh"
def apple(self):
print("i am superman")
thing = mystuff() # 实例化,得到thing这个对象。
thing.apple()
print(thing.tangerine)
将类实例化就会得到对象,可以对对象调用函数等操作。
class Song(object):
def __init__(self,lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
happy_baby = Song(["happy birthday to you","happy new year"])
happy_baby.sing_me_a_song()
大部分使用继承的场合都可以使用组合取代或简化,而多重继承则需要不惜一切地避免。
继承就是指一个类地大部分或全部功能是从一个父类中获得的,父类和字类有三种交互方式:
# 隐式继承
class parent(object):
def implicit(self):
print("parent implicit()")
class child(parent):
pass
dad = parent().implicit()
child = child().implicit()
class parent(object):
def override(self):
print("parent override()")
class child(parent):
def override(self):
print("child override()")
dad = parent().override()
child = child().override()
class parent(object):
def altered(self):
print("parent altered()")
class child(parent):
def altered(self):
print("child, before parent altered()")
super(child,self).altered()
print("child,after parent altered()")
parent().altered()
child().altered()
super(child,self)还保留着继承关系,因此通过继承父类之后,通过.altered()调用了父类的altered函数。
class parent():
def override(self):
print("parent override()")
def implicit(self):
print("parent implicit()")
def altered(self):
print("parent altered()")
class child(parent):
def override(self):
print("child override()")
def altered(self):
print("child, before parent altered()")
super(child, self).altered()
print("child,after parent altered()")
dad = parent()
son = child()
dad.implicit()
son.implicit()
dad.override()
son.override()
dad.altered()
son.altered()
class other(object):
def override(self):
print("other override()")
def implicit(self):
print("other implicit()")
def altered(self):
print("other altered()")
class child(object):
def __init__(self):
self.other = other()
def implicit(self):
self.other.implicit()
def override(self):
print("child override()")
def altered(self):
print("child, before parent altered()")
self.other.altered()
print("child,after parent altered()")
son = child()
son.implicit()
son.override()
son.altered()
这里不是使用了继承的方法,而是,child里面有一个other()用来实现继承的功能。
继承和组合说到底都是为了解决关于代码重复的问题。
每个人的代码风格不同,这里仅代表一点建议: