2018-07-04-Python全栈开发day25-静态属性、类方法、静态方法以及组合

1.静态属性property

  作用:改变类中方法的调用方式,不需要加括号,看起来和数据属性的调用方式相同

  

class Fangjian():
    tag='888'
    def __init__(self,name,owner,wedth,length):
        self.name=name
        self.owner=owner
        self.wedth=wedth
        self.length=length
    @property
    def cal(self):
        return self.wedth*self.length
p1=Fangjian('yehaibin','xuzheng',50,80)
a=p1.cal#不需要括号

2.类方法 classmethod

  作用:类中的函数属性可以使用类来直接调用,但是需要创建一个实例,这样实例和类就绑定到一块了,需要一种方式,来直接调用类中的方法

  

class Fangjian():
    tag='888'
    def __init__(self,name,owner,wedth,length):
        self.name=name
        self.owner=owner
        self.wedth=wedth
        self.length=length
@classmethod#只是给类用的,实例不要用
    def class_method(cls):
        print('this is class`s method')
Fangjian.class_method()

3.静态方法staticmethod

  作用:类似于类的工具包,在方法中不含有类和实例的调用,只是实现一个功能而已,例如输出

  

class Fangjian():
    tag='888'
    def __init__(self,name,owner,wedth,length):
        self.name=name
        self.owner=owner
        self.wedth=wedth
        self.length=lengt
 @staticmethod
    def test12():
        print('this is a test staticmethod')
p1=Fangjian('yehaibin','xuzheng',50,80)
Fangjian.test12()
p1.test12()#类和实例都可以直接调用并且使用

4.组合

  最直观的感受就是认清楚,类的方法其实就是一个字典,然后在字典中进行取值

  

#自己做一个选课系统#组合
#目的:
class School():#定义学校类, def __init__(self,name,destin): self.name=name self.destin=destin class Course: def __init__(self,name,price,priod,school): self.name=name self.prine=price self.priod=priod self.school=school#这是将课程和学校进行关联 school1=School('sdau','shandong') school2=School('sdau2','shandong2') school3=School('sdau3','shandong3') # sdau=School('sdau','shandong') # python=Course('python','100','150',sdau.name) # print(python.school)#这是自己输入的值 #尝试让用户进行判断并且输入信息 msg={ '1':school1, '2':school2, '3':school3 } while True: school_chioce=input('please chioce your school' '1:school' '2:schoo2' '3:schoo3')#让学生进行选课,选择喜欢的学校 #msg[school_chioce]#获得了用户选择的实例 school_obj=msg[school_chioce]#之前已经实例化好了几所学校,学生选好学校之后,也就是选择实例化之后的学校的其他信息,可以调用实例的方法 course_name=input('please input your name') price = input('please input your price')#根据学生的选择来实例化课程 priod = input('please input your priod') final_course=Course(course_name,price,priod,msg[school_chioce]) print('this is you course %s' %final_course.school.name,)
   if school_chioce=='q': break

猜你喜欢

转载自www.cnblogs.com/hai125698/p/9265816.html