No.010-Python-学习之路-Day7-面向对象的进阶

类中高级方法

静态方法<装饰器@staticmethod>

静态方法仅仅名义上归类管理,但实际上静态方法未利用任何的类中属性;

class Dog(object):
    def __init__(self, name):
        self.name = name
    @staticmethod # 静态方法->实际上跟类没什么关系,仅仅是一个方法,仅仅是需要使用类名来调用
    def eat(food):
        # 因为没有传self进去,则无法使用self.name之类的内容调用
        # 目的就是不在函数内使用
        # 相当于类的工具包
        print("Unknow dog is eating %s" %food)
        
d = Dog("XiLuo")
d.eat("Shit")

类方法<装饰器@classmethod>

类方法仅仅可以访问类变量,无法访问实例变量;

class Market(object):
    discount = 10.0
    goods = {"macbook": {"sn": "No.001","price": 9600,"counts": 100},
            "iphone": {"sn": "No.002","price": 5600,"counts": 50}
    }

    def __init__(self, name , owner, address):
        self.name = name
        self.owner = owner
        self.address = address

    @classmethod
    def set_discount(cls, new_discount):
        print("Discount change from %.1f to %.1f" %(cls.discount, new_discount))
        cls.discount = new_discount

    def get_price(self):
        for good in self.goods:
            print("商品名-{} 编号-{} 价格-{}".format(
                good,
                self.goods[good]['sn'],
                self.goods[good]['price'] * self.discount
            ))


mymarket = Market("小苹果百货店", "Amadeus Lee", "尚阳城")

mymarket.get_price() 
mymarket.set_discount(9.0) # 可以更改类变量discount的值
mymarket.get_price() 
Market.set_discount(8.0) # 可以更改类变量discount的值
Market.get_price(mymarket)
@classmethod

属性方法<装饰器@property>

# @ property 是把一个方法变成一个静态属性

# @ property 是把一个方法变成一个静态属性

# 属性方法如何赋值?
#   使用类似于width.setter的方法来来赋值
# 属性方法如何删除?
#   使用类似于width.deleter的方法来删除
# 把一个方法变成静态属性的作用:
#   1.将直接暴露的属性隐藏,只有通过一定的限定才能够赋值或者取值,而且仍然以属性的方式调用,而非函数
#   2.有些属性是动态的,比如航班的实时状态,如果需要取得这个值,需要执行<联系API->调用函数分析->返回结果>
#     ,这些使用属性方法直接生成,在类外看起来就是一个属性<隐藏实现细节>,而非相对复杂的函数操作;

class Screen(object):
    '''
    显示屏类,定义长和宽
    '''
    def __init__(self):
        self.__width = None
        self.__height = None

    @property # 将width变为属性,目的为了限制width相关的信息,希望其设置的值在范围内
    def width(self):
        return self.__width

    @width.setter # 可以调用方法进行修改
    def width(self, width):
        if isinstance(width, int):
            if 1366 >= width >= 1024:
                self.__width = width
            else:
                raise ValueError("width范围为1024-1366")
        else:
            raise ValueError("width不是int类型")

    @property # 将height变为属性
    def height(self):
        return self.__height

    @height.setter # 可以调用方法进行修改
    def height(self, height):
        if isinstance(height, int):
            if 768 >= height >= 256:
                self.__height = height
            else:
                raise ValueError("height的范围为256-768")
        else:
            raise ValueError("height不是int类型")

    @height.deleter # 当使用del xxx 的时候显示的信息;
    def height(self):
        self.__height = None
        print("已删除height!!!")

    @property # 这个是一个只读属性,没有定义赋值的方法哦;
    def resolution(self):
        if isinstance(self.__width, int) and isinstance(self.__height, int):
            if self.__width * self.__height == 786432:
                return "测试通过"
            else:
                return "测试失败"
        else:
            raise ValueError("width及height必须为int类型")


s = Screen()
s.width = 1024
s.height = 768
print(s.width, s.height, s.resolution)
@property定义的可操作属性及只读属性

类中的特殊方法

__init__(self) : obj init method;

__call__(self, *args, **kwargs) :Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).

__str__(self):compute the “informal” or nicely printable string representation of an object. The return value must be a string object.When a object is Called by str(object) and the built-in functions format() and print();

obj/class.__doc__: return the description of the class or class of the obj;

obj/class.__module__: the class of obj is import from which module , return the module's name;

obj.__class__: return the class of the obj;

obj/class.__dict__ : return all attribute of a class or a obj , class only include class attrubute, not include instance attribute;obj have them all;

class Dog(object):
    '''
        这个类是描述狗这个对象的
    '''
    type = "dog"
    def __init__(self):
        self.name = "Baby"

    def get_name(self):
        print("come from get_name fun", self.name)

    
    def __call__(self, *args, **kwargs):
        self.name = args[0]
        self.type = args[1]

    def __str__(self):
        return "<obj>:%s" % self.name # 可以使用打印的时候看到比如下面的print(d) # 在jango中使用较多

d = Dog()

d("Bruce", "Mydog") # call方法的调用1 # 如果涉及类变量不会更改,只会覆盖
print("obj.__call__", d.name, d.type)
Dog()("Amadeus", "yourdog") #call方法的调用2 # 如果涉及实例及类变量不会更改不会覆盖
print("class.__call__", Dog.name, Dog.type)

print(d) # 显示显示信息-->调用的是__str__(self)方法

print(Dog.__doc__) # 打印这个类的描述信息
print(d.__doc__) # 打印这个类的描述信息

print("__module__",Dog.__module__, d.__module__) # 表示当前操作的对象的模块,即是从哪个模块导入的
print("__module__",d.__class__) # 表示当前的对象属于什么类


print(Dog.__dict__) #类调用打印类里的所有属性,不包括实例属性
print(d.__dict__) # 实例调用,打印实例中的属性
d.age = 2
print(d.__dict__) # 实例调用,打印实例中的属性
类特殊方法实例、

__getitem__(self, key): # 在使用obj[xxx]取值时即调用这个方法

__setitem__(self, key, value): # 在使用obj[key] = value赋值使,使用这个方法

__delitem__(self, key): # 在使用del obj[key] 时调用这个函数,具体操作自定义

class Foo(object):  # 自封装字典 # 2.7里面可以变成列表,3.0里面没有

    def __init__(self):
        self.dic = {}

    def __getitem__(self, key): # 在使用obj[xxx]取值时即调用这个方法
        print('__getitem__', key)
        return self.dic[key]

    def __setitem__(self, key, value): # 在使用obj[key] = value赋值使,使用这个方法
        print('__setitem__', key, value)
        self.dic[key] = value

    def __delitem__(self, key): # 在使用del obj[key] 时调用这个函数,具体操作自定义
        print('__delitem__', key)
        self.dic.pop(key)

obj = Foo()
obj['name'] = "Bruce"
obj['age'] = 19
del obj['name']
print(obj)
try:
    print(obj['name'])
except KeyError as KeyNotFound:
    print("key-name已经被删除!")
print(obj['age'])
自封装字典类型

end

猜你喜欢

转载自www.cnblogs.com/FcBlogPythonLinux/p/12295200.html