cookbook_类与对象
class Pair: def __init__(self,x,y): self.x = x self.y = y def __str__(self): return "(%s,%s)"%(self.x,self.y) def __repr__(self): return "Pair(%s,%s)"%(self.x,self.y) p = Pair(2,5) print(p) print("p is {0!r}".format(p))
_formats = { "ymd":"{d.year}-{d.month}-{d.day}", "mdy":"{d.month}/{d.day}/{d.year}", "dmy":"{d.day}/{d.month}/{d.year}" } class Date: def __init__(self,year,month,day): self.year = year self.month = month self.day = day def __format__(self,code): if code == "": code = "ymd" fmt = _formats[code] return fmt.format(d = self) d = Date(2018,9,26) print(format(d)) print(format(d,"dmy")) print(format(d,"mdy"))
from socket import socket,AF_INET,SOCK_STREAM class LazyConnection: def __init__(self,address,family = AF_INET, type = SOCK_STREAM): self.address = address self.family = family self.type = type self.sock = None def __enter__(self): if self.sock is not None: raise RuntimeError("Already connected") self.sock = socket(self.family,self.type) self.sock.connect(self.address) return self.sock def __exit__(self, exc_type, exc_val, exc_tb): self.sock.close() self.sock = None conn = LazyConnection("www.baidu.com") with conn as s: s.send(b'hahhahah')
class Date: __slots__ = ["year","month","day"] def __init__(self,year,month,day): self.year = year self.month = month self.day = day
class A: def __init__(self): self._name = "jiaojianglong" self.age = 24 def _internal_method(self): print("i am a internal method") a = A() print(a._name) #jiaojianglong
class B: def __init__(self): self.__name = "jiaojianglong" b = B() # print(b.__name)#AttributeError: 'B' object has no attribute '__name' print(b._B__name)#jiaojianglong
class C(B): def __init__(self): super().__init__() c = C() print(c._B__name)#jiaojianglong
class Person: def __init__(self,first_name): self.first_name = first_name @property def first_name(self): return self._first_name @first_name.setter def first_name(self,value): if not isinstance(value,str): raise TypeError("Excepted a string") self._first_name = value p = Person("jiao") print(p.first_name)
class A: def spam(self): print("A.spam") class B(A): def spam(self): print("B.spam") super().spam() b = B().spam()#B.spam,A.spam print(B.__mro__)#(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
class Integer(): def __init__(self,name): self.name = name def __get__(self, instance, owner): if instance is None: return self else: return instance.__dict__[self.name] def __set__(self, instance, value): if not isinstance(value,int): raise TypeError("Expected an int") instance.__dict__[self.name] = value def __delete__(self, instance): del instance.__dict__[self.name] class Point: x = Integer("x") y = Integer("y") def __init__(self,x,y): self.x = x self.y = y p = Point(2,3) print(p.x)#2 p.y = 5 print(p.y)#5 # p.x = "a"#TypeError: Expected an int print(Point.x)#<__main__.Integer object at 0x00000141E2ABB5F8>
class Point: def __init__(self,x,y): self.x = Integer("x") self.y = Integer("y") self.x = x self.y = y p = Point(2,"c") print(p.x)#2 print(p.y)#c class Typed: def __init__(self,name,expected_type): self.name = name self.expected_type = expected_type def __get__(self, instance, owner): if instance is None: return self else: return instance.__dict__[self.name] def __set__(self, instance, value): if not isinstance(value,self.expected_type): raise TypeError("Expected %s"%self.expected_type) instance.__dict__[self.name] = value def __delete__(self, instance): del instance.__dict__[self.name] def typeassert(**kwargs): def decorate(cls): for name,expected_type in kwargs.items(): setattr(cls,name,Typed(name,expected_type)) return cls return decorate @typeassert(name=str,shares = int,price=float) class Stock: def __init__(self,name,shares,price): self.name = name self.shares = shares self.price = price