本文实例讲述了Python面向对象class类属性及子类用法。分享给大家供大家参考,具体如下:c
本文实例讲述了Python面向对象class类属性及子类用法。分享给大家供大家参考,具体如下:
class类属性
class Foo(object):
x=1.5
foo=Foo()
print foo.x#通过实例访问类属性
>>>1.5
print Foo.x #通过类访问类属性
>>>1.5
foo.x=1.7 #只改新实例属性,不会改变类属性
print foo.x
>>>1.7
print Foo.x
>>>1.5
foo.x+=0.2 ##只改新实例属性,不会改变类属性
print foo.x
>>>1.9
print Foo.x
>>>1.5
del foo.x ##删除更新的实例属性,默认变为类的属性
print foo.x
>>>1.5
print Foo.x
>>>1.5
class子类
父类:
class AddrBookEntry(object):
"address book entry class"
def __init__(self, nm, ph):
self.name = nm
self.phone = ph
print "created instance for:", self.name
def updatePhone(self, newph):
self.phone = newph
print "updated phone# for:", self.name
子类:
当一个类被派生出来,子类就继承了基类的属性。所以EmplAddrBookEntry继承了AddrBookEntry的updatePhone的方法。子类最好自定义自己的构造器,不然基类的构造器会被调用。如果子类重写了基类的构造器,基类的构造器就不会自动调用,除非被显示声明出来。
class EmplAddrBookEntry(AddrBookEntry):
"employee address book entry class"
def __init__(self, nm, ph, id, em):##重写基类构造器
AddrBookEntry.__init__(self, nm, ph)
self.empid = id
self.email = em
def updateEmail(self, newem):
self.email = newem
print "updated e-mail address for:", self.name
使用子类:
john = EmplAddrBookEntry("john doe","408-555-1212", 42, "john@spam.doe")
created instance for: john doe
>>> john
<__main__.EmplAddrBookEntry object at 0x02115FD0>
>>> john.name
'john doe'
>>> john.phone
'408-555-1212'
>>> john.email
'john@spam.doe'
>>> john.updatePhone("415-555-1212")
updated phone# for: john doe
>>> john.phone
'415-555-1212'
>>> john.updateEmail("john@doe.spam")
updated e-mail address for: john doe
>>> john.email
'john@doe.spam'
Python
面向对象
class
类属性
子类