Five, Python 3 facing the object, the instance variables

3, instance variables

1) Constructor

Description :

  • Constructor is a special instance method, the method _ called the init _, used to initialize instance variables of an object
  • When you create an object, automatically call the constructor
  • If there is no class constructor is defined, Python will automatically define a default constructor parameter containing only one self class
class Person:
    # 构造方法
    def __init__(self, name='无名氏', age=0):
        print('构造方法')
        self.name = name
        self.age = age

2) Create Object

Description : call the constructor method, not directly call _ the init _ method, but is called by the class name.

P1 = Person()      # 创建对象
print('P1:', P1.name, P1.age)     # 访问实例变量:对象.实例变量
print('-'*30)

P2 = Person('孙悟空')
print('P2:', P2.name, P2.age)
print('-'*30)

P3 = Person(age=25)
print('P3:', P3.name, P3.age)
print('-'*30)

P4 = Person('白骨精',18)
print('P4:', P4.name, P4.age)
构造方法
P1: 无名氏 0
------------------------------
构造方法
P2: 孙悟空 0
------------------------------
构造方法
P3: 无名氏 25
------------------------------
构造方法
P4: 白骨精 18

3) Operation instance variables

Object invokes an instance variable :

  • access
  • Change: the existing instance variable assignment
  • Increased: for instance variables do not exist assignment
  • Delete: the del statement
class Item:
    def __init__(self,name='鼠标'):
        self.name = name

# 操作实例变量
im1 = Item()
print(im1.name)      # 访问实例变量
print('-'*30)

im2 = Item('显示器')
print(im2.name)      # 改变实例变量
print('-'*30)

im2.color = '黑色'   # 新增实例变量
print(im2.name, im2.color)
print('-'*30)

del im2.color       # 删除实例变量
鼠标
------------------------------
显示器
------------------------------
显示器 黑色
------------------------------

Guess you like

Origin blog.csdn.net/qq_36512295/article/details/94547491