zoukankan      html  css  js  c++  java
  • property,类方法和静态方法

    # from math import pi
    #
    # class Circle:
    #     def __init__(self, r):
    #         self.r = r
    #
    #     @property
    #     def perimeter(self):
    #         return 2*pi*self.r
    #
    #     @property
    #     def area(self):
    #         return self.r**2*pi
    #
    # circle = Circle(4)
    # print(circle.perimeter)
    # print(circle.area)
    
    # class Person:
    #     discount = 0.8
    #     def __init__(self, name):
    #         self.__name = name
    #         self.price = 20
    #
    #     @property
    #     def name(self):
    #         return self.__name
    #
    #     @name.deleter
    #     def name(self):
    #         return self.__name
    #
    #     @name.setter
    #     def name(self, new_name):
    #         self.__name = new_name
    #
    # person = Person('aaa')
    # print(person.name)
    # person.name = 'bbb'
    # del person.name
    # print(person.name)
    
    
    class Person:
        age = 1
        def __init__(self, name):
            self.__name = name
    
        @property                # 把方法变成属性
        def name(self):
            return self.__name
    
    
        @classmethod            # 把方法变成类方法,这个方法就直接可以被类调用,不需要依托任何对象
        def get_age(cls, age):
            cls.age = age
    
    # 如果一个函数 既和对象没有关系 也和类没有关系 那么就用staticmethod将这个函数变成静态方法
        @staticmethod
        def get_usr_pwd():
            usr = input('input user:')
            pwd = input('input password')
            print('user is %s, password is %s' %(usr, pwd))
    
    person = Person('aaa')
    print(person.name)
    Person.get_age(54)
    Person.get_usr_pwd()
  • 相关阅读:
    取某个关键词以及之后的数据
    从SQL下载大量数据到Excel
    SQL 分页
    whereis linux文件搜索
    crontab Linux定时器工具
    Angular
    工具
    百度OAuth2.0登录
    JS事件学习 拖拽,鼠标键盘事件实例汇总
    信息栏滚动效果学习总结
  • 原文地址:https://www.cnblogs.com/hhsh/p/9643551.html
Copyright © 2011-2022 走看看