python基础九

class Chinese:
    #数据属性
    name = 'xiaoming'

    def __init__(self,a,b,c):
        self.a = a
        self.b = b
        self.c = c
        print('666')

    def method2(self):
        print('77777')
    #函数属性
    def method1(self):
        print('%s吃掉了fengfeng' %self.a)
    def eat_food(self,food):
        print('%s 正在吃 %s' %(self.a,food))

p1 = Chinese('a','b','c')
print(p1)
print(p1.name)
print(p1.__dict__)
Chinese.method1(p1)
#TypeError: method2() takes 0 positional arguments but 1 was given
p1.method2()

p1.eat_food('米饭')

p2 = Chinese('dou',18,'man')
p2.eat_food('面条')
print(dir(p2))
#类属性的增删改查
Chinese.s = 'gege'
print(Chinese.s)
def add_mothod():
    print('添加一个方法')
Chinese.add_new_method = add_mothod

print(Chinese.__dict__)
#调用
Chinese.add_new_method()
del  Chinese.s

print(Chinese.__dict__)
#实例属性的增删改查
p3 = Chinese('meimei',17,'women')
p3.a = 'xiaoliu'
p3.method1()

def new_mothod1():
    print("实例添加方法")
p3.new_method1 = new_mothod1
#调用
p3.new_method1()

class Car:
    l = ['a','b','c']
    def __init__(self,a):
        self.name = a
        print('初始化方法')
    def method1(self):
        print('方法执行了')

p1 = Car('fengfeng')
#此时相当于在实例化的p1中增加了一个list
# p1.l = ['a','b','c']
# print(p1.l)
# print(Car.l)
#此时相当于在类中的list中追加一个字段
p1.l.append('d')
print(p1.l)
print(Car.l)
print(Car.__dict__)
print(p1.__dict__)

#静态属性
p1.method1
#类方法
Car.tell_info('newssss')

class Room:
    tag = 1
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

    @property
    def method1(self):
        print('静态属性')
    @classmethod
    def method2(self):
        print('类方法')
    @staticmethod
    def method3(a,b,c):
        print(a,b,c,'静态方法只是类的工具包')
#实例调用会默认将自己作为参数传进去。。。。。###实例只有数据属性,没有函数属性
r1 = Room('fengfeng',11,'man')
#静态属性
r1.method1
#类方法
Room.method2()
#静态方法
Room.method3(1,2,3)
r1.method3(4,5,6)
print(Room.__dict__)
print(r1.__dict__)

组合

class School:
    def __init__(self,name,addr):
        self.name = name
        self.addr = addr
    def zhao_sheng(self):
        print('%s 正在招生' %self.name)

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

s1 = School('heima','北京')
s2 = School('heima','上海')
s3 = School('heima','广州')

msg = '''
1 heima 北京校区
2 heima 上海校区
3 heima 广州校区
'''
while True:
    print(msg)
    menu = {
        '1':s1,
        '2':s2,
        '3':s3
    }
    choice = input('选择学校:')
    school_obj  = menu[choice]
    name = input('课程名>>: ')
    price = input('课程费用>>: ')
    period = input('课程周期>>: ')
    new_course = Course(name,price,period,school_obj)
    print('课程【%s】属于【%s】学校' % (new_course.name, new_course.school.name))

你可能感兴趣的:(python基础九)