Python全栈学习笔记day 23:面向对象2、命名空间、组合

__init__方法 :初始化方法
    python帮我们创建了一个对象self
    每当我们调用类的时候就会自动触发这个方法。默认传self
    在init方法里面可以对self进行赋值
self:
    self拥有属性都属于对象
    在类的内部,self就是一个对象

类可以定义两种属性:静态属性、动态属性
类中的静态变量:可以被对象和类调用
对于不可变数据类型来说,类变量最好用类名操作
对于可变数据类型来说,对象名的修改是共享的,重新赋值是独立的

栗子:

class Person:
    money = 0
    def work(self):
        Person.money += 1000

mother = Person()
father = Person()
mother.money += 1000
father.money += 1000
print(Person.money)          输出:0
class Person:
    money = 0
    def work(self):
        Person.money += 1000

mother = Person()
father = Person()
Person.money += 1000
Person.money += 1000
print(Person.money)        输出:2000
栗子2:创建一个类,每实例化一个对象就计数,最终所有的对象共享这个数据
class Foo:
    count = 0
    def __init__(self):
        Foo.count += 1

f1 = Foo()
f2 = Foo()
print(f1.count)            2
print(f2.count)            2
f3 = Foo()
print(f1.count)            3
组合 :一个对象的属性值是另外一个类的对象   在下面这个例子中:
    对象:alex  属性值:weapon 是 weapon的对象

栗子2:创建一个老师类,老师有生日,生日也是一个类,要使用组合

class Birthday:
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day

class Course:
    def __init__(self,course_name,period,price):
        self.name = course_name
        self.period = period
        self.price = price

class Teacher:
    def __init__(self,name,age,sex,birthday):
        self.name = name
        self.age = age
        self.sex = sex
        self.birthday =birthday
        self.course = Course('python','6 month',2000)

b = Birthday(2018,1,16)
egg = Teacher('egon',0,'女',b)
print(egg.name)
print(egg.birthday.year)    组合
print(b.year)
print(egg.birthday.month)    组合
print(b.month)
print(egg.course.price)        组合

猜你喜欢

转载自blog.csdn.net/qq_35883464/article/details/83622649