【原】Python基础-__init__

#py中,有些名称前后都会加上俩个下划线,是有特殊含义的
#在Py中,由这些名字组成的集合所包含的方法称为 “魔法方法”。如果在你的对象中
#实现了这些方法的其中某一个,那这些方法会被py自动调用,几乎没有必要自己调用。比如
#构造方法,在类中定义 __init__就可以。
class FooBar:
var = "none"
def __init__(self):
self.var = "init var"

f = FooBar()
print(f.var)

#构造方法有参数的情况
class FooBar2:
var = "none"
def __init__(self, value):
self.var = value

f2 = FooBar2("sysnap xxxx")
print(f2.var)

#类的继承
class ClassA:
def hello(self):
print("hello in class A")

class ClassB(ClassA):
pass
a = ClassA()
a.hello() #输出 hello in class A

b = ClassB()
b.hello() #输出hello in class A
del a, b

#类继承中,方法的重写
class ClassA_1:
def hello(self):
print("hello class a")
class ClassB_1(ClassA_1):
def hello(self): #重写了a中的hello方法
print("hello class b")
a = ClassA_1()
a.hello() #输出hello class a

b = ClassB_1()
b.hello() #输出hello class b

#继承类中重写构造方法,有个问题,就是父类的构造方法不会被调用到,使用supper函数
class Brid:
def __init__(self):
self.hungry = 1
def eat(self):
if self.hungry == 1:
print("i am hungry!\n")
self.hungry = 0
else:
print("i am not hungry!\n")

class SongBird(Brid):
def __init__(self):
super(SongBird, self).__init__()
self.sound = "ko ko"
def sing(self):
print(self.sound)

sbird = SongBird()
sbird.eat()
sbird.eat()
sbird.sing()

posted @ 2013-11-25 20:52  sysnap  阅读(199)  评论(0编辑  收藏  举报