Python类的实例属性详解

  实例属性

  1.类被实例化后才会具有的属性

  2.一般在_init_()方法中创建并初始化

  3.直接使用即定义:self.<属性名>

  4.引用方法:self.<属性名>

  5.self用来表示类的实例的

  例如:在类TestCss当中定义实例属性

  class TestCss:

  cssa = 'class-attribe'

  def __init__(self):

  self.a = 0

  self.b = 10

  def info(self):

  print('a:',self.a,'b:',self.b)

  if __name__ == '__main__':

  tc = TestCss()

  tc.info()

  程序的运行结果为:

    6.类外用实例名.属性名方式定义和引用

  例如:

  class TestCss:

  cssa = 'class-attribe'

  def __init__(self):

  self.a = 0

  self.b = 10

  def info(self):

  print('a:',self.a,'b:',self.b)

  if __name__ == '__main__':

  tc = TestCss()

  tc.info()

  if __name__ == '__main__':

  tc = TestCss()

  tc.info()

  tc.color = 'red'

  print(tc.color)

  程序的运行结果为:

    7.相同类的不同实例其实例属性是不相关的

  例如:

  lass TestCss:

  cssa = 'class-attribe'

  def __init__(self):

  self.a = 0

  self.b = 10

  def info(self):

  print('a:',self.a,'b:',self.b)

  if __name__ == '__main__':

  tc = TestCss()

  tc.info()

  tc = TestCss()

  tca = TestCss()

  tc.a = 100

  tc.b = 200

  tc.info()

  tca.info()

  程序的运行结果为:

  8.一般不建议在_init_()方法之外中创建和初始化实例属性

  9.一般不推荐类外定义和修改,修改可以单独定义方法。

原文链接:http://www.maiziedu.com/wiki/python/instance/

原文地址:https://www.cnblogs.com/space007/p/6051506.html