python基础 第六章:class

#Set(can remove the repeat item of the list)&&can be indexed
a_set = {1,2,3,4}
print(a_set)
a_set.add(5)
print(a_set)
a_set.discard(5)
print(a_set)
a_set.add(2)
print(a_set)#{1, 2, 3, 4}
bset={2,1,5,4,7,6}
print(sorted(bset))
num_list ={9,6,5,7,8,4}
print(sorted(num_list))
#the result above
'''
=============== RESTART: /Users/apple/Documents/FiveChapter.py ===============
{1, 2, 3, 4}
{1, 2, 3, 4, 5}
{1, 2, 3, 4}
{1, 2, 3, 4}
[1, 2, 4, 5, 6, 7]
[4, 5, 6, 7, 8, 9]
'''
a_list = {3,5,7,9,1,2}
b_list = {6,7,8,9}
for a,b in zip(a_list,b_list):
    print(b,'is',a)
a = [j**2 for j in range(1,10)]
c=[j+1 for j in range(1,10)]
k=[n for n in range(1,10) if n%2 ==0]
z=[letter.lower() for letter in 'ABCDEFG']
print(a)
print(c)
print(k)
print(z)
#result
'''
8 is 1
9 is 2
6 is 3
7 is 5
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8]
['a', 'b', 'c', 'd', 'e', 'f', 'g']
'''
letters =['a','b','c','d','e']
for num,letter in enumerate(letters):
    print(letter, 'is',num+1)
'''
a is 1
b is 2
c is 3
d is 4
e is 5
'''
#setup Class
class CocaCola:
    formula =['caffeine','sugar','water','soda']
    #self is equal with coke_for_me class instance an so on
    def drink(self):
        print('energy!')
    def drinka(self,how_much):
        if how_much =='a sip':
            print('so Cool~')
        elif how_much =='whole bootle':
            print('Headache!')
##setup Class instance
coke_for_me = CocaCola()
coke_for_you =CocaCola()
coke_for_me.drink()
coke_for_me.drinka('whole bootle')
print(CocaCola.formula)
print(coke_for_me.formula)
print(coke_for_you.formula)
for element in coke_for_me.formula:
    print(element)
#result
'''
energy!
Headache!
['caffeine', 'sugar', 'water', 'soda']
['caffeine', 'sugar', 'water', 'soda']
['caffeine', 'sugar', 'water', 'soda']
caffeine
sugar
water
soda
'''
#magic function _init_()
class CocaCola1:
    formula =['caffeine','sugar','water','soda']
    def _init_(self):
        for element in self.formula:
            print('coke has {}!'.format(element))
    def drink(self):
        print('energy!')
coke = CocaCola1()

class CocaCola2:
    formula =['caffeine','sugar','water','soda']
    def _init_(self,logo_name):
       self.local_logo=logo_name
    def drink(self):
        print('energy!')
#coke1 = CocaCola2('a')
#coke1.local_logo
coke1=CocaCola2()
coke1.drink()
#coke1 =CoCaCola2('aaaaa')


猜你喜欢

转载自blog.csdn.net/zjguilai/article/details/89291350