"""
__len__,__hash__,__eq__这些都是类中默认有的方法
"""
a, b = 3, 2
len()
hash()
print(a == b)
del析构方法
class A(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return "%s-%s" % (self.name, self.age)
def __str__(self):
return "名字%s-年龄%s" % (self.name, self.age)
def __del__(self):
print("%s被终结了!!!" % self.name)
a1 = A("小张", 18)
print(repr(a1))
print(str(a1))
del a1
print(a1)
new方法
class People(object):
foods = []
a = None
def __init__(self, name):
self.name = name
def buy_food(self, food):
self.foods.append(food)
print("%s买了%s" % (self.name, food))
def __new__(cls, *args, **kwargs):
if cls.a is None:
obj = object.__new__(cls)
print(obj)
cls.a = obj
return cls.a
p1 = People("小工")
p2 = People("小红")
p3 = People("小慌")
print(p1, p2, p3)
p1.buy_food("樱桃")
p2.buy_food("牛肉")
p3.buy_food("海鲜")
Call方法(对象+括号)几乎不用
class People(object):
def __init__(self, name):
self.name = name
def __call__(self, *args, **kwargs):
print(args, kwargs)
p1 = People("哈萨德")
p1("sadsad")
People("dasd")("45655")
isinstance/issubclass
class Student(object):
pass
s1 = Student()
print(isinstance(s1, Student))
print(issubclass(Student, object))
类的其他创建方式(不推荐,但是要知道)
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print("%s在学习" % self.name)
a = type("Student", (object,), {"type": "people", "__init__": __init__, "run": run})
s1 = a("小张",18)
s1.run()
print(s1.name,s1.age)