类的定义及类中属性的访问

!!!类的定义及类中属性的访问备忘录

类与对象的关系:类是对象的抽象,对象是类的具体体现
类的简单定义及对象的访问:

class Myself():
    name = '小白'
    sex = 'man'
    hobby = 'coding'
    def introduce(self):
        print('大家好,我是%s'%self.name)
pre = Myself()
print(pre.name)
print(pre.sex)
print(pre.hobby)
pre.introduce()

这样就简单的定义了一个类,但如果我们想改变类中的参数,可以如下实现:

class Myself():
    name = '小白'
    sex = 'man'
    hobby = 'coding'
    def introduce(self):
        print('大家好,我是%s'%self.name)
pre = Myself()
Myself.name = 'Mary'
Myself.sex = 'women'
Myself.hobby = 'shopping'
print(pre.name)
print(pre.sex)
print(pre.hobby)
pre.introduce()

这里我们发现,这样改变类中的参数很繁琐,便引入了下面这种构造的方法:

class Myself():
    def __init__(self,name,sex,hobby):
        self.name = name
        self.sex = sex
        self.hobby = hobby
    def introduce(self):
        print('大家好,我是%s'%self.name)

pre = Myself('小白','man','coding')
pre2 = Myself('Mary','woman','shopping')
print(pre.name)
print(pre.sex)
print(pre.hobby)
pre.introduce()
print(pre2.name)
print(pre2.sex)
print(pre2.hobby)
pre2.introduce()

你可能感兴趣的:(_python)