python new 干什么用_[py]python中__new__作用

47562994641dbff508020b1c158d63ee.png

__new__的作用: 元类

class Author(type):

# 类对象 类名 父类 类属性和方法

def __new__(mcs, name, bases, dict):

# 添加作者属性

dict["author"] = "mm"

return super(Author, mcs).__new__(mcs, name, bases, dict)

class Foo(object, metaclass=Author):

pass

foo = Foo()

print(foo.author)

创建类

def fn(self):

print("maotai")

# 类名 父类 属性

Hello = type("Hello", (object,), dict(hello=lambda x: x + 1))

h = Hello()

h.hello(12)

## type

# 1,同__class__, 实例属于哪一类 类属于哪一类

# 2,创建一个类

匿名函数

g = lambda x: x + 1

print(g(1))

self是什么

class A:

# self是什么

def __init__(self):

print(self)

a = A()

print("--->",a)

cls的含义

class A:

## cls的含义

@classmethod

def show(cls,name):

print("A",name)

a = A()

a.show("maota")

子类调用父类方法super

class A:

def show(self):

print("hello A")

class B(A):

def show2(self):

super().show() # 调用父类方法

b = B()

b.show2()

类的属性和方法

class A:

age = 22

def __init__(self):

self.name = 'maotai'

def show(self):

pass

## dir(A) 有age, show 类的属性和方法

## dir(A()) 有name和age,show 实例的属性和方法

for i in dir(A()):

print(i)

print(A.__dict__) # age show 类属性和方法

# __doc__

# __init__

# __dict_

# __dir__

# __class__

# __delattr__

# __new__

# __repr__

# __setattr__

@property和__call__ 与 callable()

class Person:

# 对象当作属性来调用

@property

def show(self):

print("mao tai")

# 打印实例()时候的显示

def __call__(self, *args, **kwargs):

print("hello maotai")

p = Person()

# p() # hello maotai

# TypeError: 'Person' object is not callable

p.show # mao tai

print(callable(p)) # True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值