温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中class类属性及子类怎么用

发布时间:2021-08-03 12:27:10 来源:亿速云 阅读:90 作者:小新 栏目:开发技术

小编给大家分享一下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类属性及子类怎么用”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI