我的Python第五篇 面向对象

一、类(class)的定义
1.定义一个类

>>> class Cocacola:
    formula = ['caffeine','sugar','water','soda']
    def drink(self):
        print('Energy!')


>>> 
>>> coke_for_me = Cocacola()
>>> coke_for_you = Cocacola()
>>> coke_for_me.formula
['caffeine', 'sugar', 'water', 'soda']
>>> coke_for_me.drink()
Energy!
>>> 

2.类的属性
在类当中赋值的变量,就是类的变量,就是类的属性。

>>> class Cocacola:
    formula = ['caffeine','sugar','water','soda']
>>> coke_for_me = Cocacola()
>>> coke_for_me.formula
['caffeine', 'sugar', 'water', 'soda']

3.类的实例化
将类的定义赋予一个实例

>>> class Cocacola:
    formula = ['caffeine','sugar','water','soda']
>>> coke_for_me = Cocacola()
>>> coke_for_me.formula
['caffeine', 'sugar', 'water', 'soda']

4.类属性的引用
类的实例可以引用类的属性,类的属性会被类的实例共享。类的属性可以遍历。

>>> 
>>> Cocacola.formula
['caffeine', 'sugar', 'water', 'soda']
>>> coke_for_me.formula
['caffeine', 'sugar', 'water', 'soda']
>>> coke_for_you.formula
['caffeine', 'sugar', 'water', 'soda']
>>> 
>>> 
>>> for i in Cocacola.formula:
    print(i)


caffeine
sugar
water
soda

>>> for i in coke_for_me.formula:
    print(i)


caffeine
sugar
water
soda
>>> 

5.实例属性
实例可以赋值新的变量,实例的变量就是实例的属性。

>>> 
>>> class Cocacola:
    formula = ['caffeine', 'sugar', 'water', 'soda']


>>> coke_for_me = Cocacola()
>>> coke_for_me.new_taste = 'cherry'
>>> print(coke_for_me.new_taste)
cherry
>>> 

6.实例方法
A.

>>> 
>>> class Person:
    def sport(self):
        print('Run!')
        print('Jump!')


>>> xiaoming = Person()
>>> xiaoming.sport() # 这里不需要输入参数
Run!
Jump!
>>> 

B.更多的参数:

>>> 
>>> class Beer:
    formula = ['Hops','Malt_dust','yeast','wather']
    def drink(self,how_much):
        if how_much == 'a sip':
            print('Cool~~')
        elif how_much == 'whole bottle':
            print('Headache!')


>>> Tsingtao_Beer = Beer()
>>> Tsingtao_Beer.drink('a sip')
Cool~~
>>> Tsingtao_Beer.drink('whole bottle')
Headache!
>>> 

8.self
被创建的实例本身,将一个对象作为一个参数放入函数中。如果类的方法中只有一个self,则类的实例引用方法时不需要再额外填入一个参数。
9.__init__() 魔术方法
初始化,可以在类中直接创建实例的方法并加以引用。

>>> 
>>> class Beer:
    formula = ['Hops','Malt_dust','yeast','wather']
    def __init__(self):
        for element in self.formula:
            print('The beer has {}'.format(element))


>>> Tsingtao_Beer = Beer('青岛啤酒')
The beer has Hops
The beer has Malt_dust
The beer has yeast
The beer has wather
>>> 

二、类的继承

你可能感兴趣的:(我的python,python)