cookbook_类与对象
程序员文章站
2022-10-25 22:05:00
1修改实例的字符串表示 可以通过定义__str__()和__repr__()方法来实现 对于__repr__(),标准的方法是让他产生的字符串文本能够满足eval(repr(x)) == x __str__()则产生一段有意义的文本 2自定义字符串的输出格式 我们想让对象通过format()函数和字 ......
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
上一篇: 联芸Maxio展示国产PCIe SSD主控:速度可达3.5GB/s
下一篇: 安装centos8