Python基础系列

Python面向对象之定制对象独有特征

2019-08-16  本文已影响6人  我爱学python

类中定义的函数是类的函数属性,类可以使用,但使用的就是一个普通的函数而已,意味着需要完全遵循函数的参数规则,该传几个值就传几个

一、引入

class OldboyStudent:
    school = 'oldboy'

    def choose_course(self):
        print('is choosing course')


stu1 = OldboyStudent()
stu2 = OldboyStudent()
stu3 = OldboyStudent()
OldboyStudent.school = 'OLDBOY'
print(stu1.school)
OLDBOY
print(stu2.school)
OLDBOY

二、定制对象独有特征

print(stu1.__dict__)
{}
print(stu2.__dict__)
{}
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
stu1.name = 'tank'
stu1.age = 18
stu1.gender = 'male'

print(stu1.name, stu1.age, stu1.gender)
tank 18 male
try:
    print(stu2.name, stu2.age, stu2.gender)
except Exception as e:
    print(e)
'OldboyStudent' object has no attribute 'name'
stu2.name = 'sean'
stu2.age = 19
stu2.gender = 'female'

print(stu2.name, stu2.age, stu2.gender)
sean 19 female

三、属性查找

四、类定义阶段定制属性

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def init(obj, x, y, z):
    obj.name = x
    obj.age = y
    obj.gender = z


init(stu1, 'tank1', 181, 'male1')
print(stu1.name, stu1.age, stu1.gender)
tank1 181 male1
init(stu2, 'sean1', 191, 'female1')
print(stu2.name, stu2.age, stu2.gender)
sean1 191 female1
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class OldboyStudent:
    school = 'oldboy'

    def __init__(self, name, age, gender):
        """调用类的时候自动触发"""
        self.name = name
        self.age = age
        self.gender = gender
        print('*' * 50)

    def choose_course(self):
        print('is choosing course')


try:
    stu1 = OldboyStudent()
except Exception as e:
    print(e)
__init__() missing 3 required positional arguments: 'name', 'age', and 'gender'
stu1 = OldboyStudent('nick', 18, 'male')
**************************************************
print(stu1.__dict__)
{'name': 'nick', 'age': 18, 'gender': 'male'}
上一篇下一篇

猜你喜欢

热点阅读