zoukankan      html  css  js  c++  java
  • 【python】属性和类方法

    #属性的初识

    class Person:

        def __init__(self,name,hight,weight):

            self.name = name

            self.__hight = hight

            self.__weight = weight

        @property

        def bmi(self):

            return '%s 的bmi 值%s' %(self.name,self.__weight / self.__hight ** 2)

    p1 = Person('大阳哥',1.68,70)

    # print(p1.bmi())

    print(p1.bmi)

    # 属性  : 将一个方法伪装成一个属性,在代码的级别上没有本质的提升,但是让其看起来跟合理.

    P1.bmi = 25 #常规修改属性值会报错

    # 属性的改

    class Person:

        def __init__(self,name,age):

            self.name = name

            if type(age) is int:

                self.__age = age

            else:

                print( '你输入的年龄的类型有误,请输入数字')

        @property

        def age(self):

            return self.__age

        @age.setter

        def age(self,a1):

            '''判断,你修改的年龄必须是数字'''

            if type(a1) is int:

                self.__age = a1

            else:

                print('你输入的年龄的类型有误,请输入数字')

        @age.deleter

        def age(self):

            del self.__age

    p1 = Person('帅哥',20)

    print(p1.age) #使用@property 将一个方法伪装成一个属性,否则直接会报错

    p1.age = 23  #使用@方法名.setter 可对伪装后的属性值进行修改 不常用

    print(p1.age)

    del p1.age #使用@方法名.deleter 可对伪装后的属性进行删除 不常用

    2、类方法:

    1、@classmethod  类方法的装饰器,内置函数

    class A:

        def func(self):  # 普通方法

            print(self)

        @classmethod  # 类方法

        def func1(cls):

            print(cls)

    # a1 = A()

    # a1.func()

    # A.func(a1)

    # 类方法: 通过类名调用的方法,类方法中第一个参数约定俗称cls,python自动将类名(类空间)传给cls.谁调传谁

    A.func1()

    使用场景:

        1,无需对象参与.不用对象命名空间中的内容,用到类命名空间中的变量(静态属性)

        2,对类中的静态变量进行修改.

    使用类方法:

     

     3、静态方法

    -----------------------------------待补充------------------------------

  • 相关阅读:
    HDU 5059 Help him
    HDU 5058 So easy
    HDU 5056 Boring count
    HDU 5055 Bob and math problem
    HDU 5054 Alice and Bob
    HDU 5019 Revenge of GCD
    HDU 5018 Revenge of Fibonacci
    HDU 1556 Color the ball
    CodeForces 702D Road to Post Office
    CodeForces 702C Cellular Network
  • 原文地址:https://www.cnblogs.com/xlzhangq/p/13211290.html
Copyright © 2011-2022 走看看