Python面試 類的特殊方法

2021-08-17 05:15:54 字數 2625 閱讀 4168

class

foo():

def__init__

(self):

print("foo-init")

def__call__

(self):

print("foo-call")

f = foo()

f() # 過載了括號運算子

"""foo-init

foo-call

"""

class

decorator

():def

__init__

(self, func):

print("decorator-init")

self.fun = func

def__call__

(self, args1, args2):

print("decorator-call")

self.fun(args1, args2)

@decorator

defadd

(a, b):

print("a+b:", a+b)

# add(1, 2)

"""decorator-init

decorator-call

a+b: 3

"""

class

mytuple

(tuple):

def__init__

(self, seq):

print("mytuple-init")

print("self:", self)

# takes no parameters

super(mytuple, self).__init__()

def__new__

(cls, seq):

print("mytuple-new")

# 過濾

g = [i for i in seq if isinstance(i ,int)]

# 返回物件:self

return super(mytuple, cls).__new__(cls, g)

t = mytuple([1, 2, "-1"])

print(type(t), t)

"""mytuple-new

mytuple-init

self: (1, 2)

(1, 2)

"""

# 描述符 : 允許你自定義在引用乙個物件屬性時應該完成的事情

# __set__:在設計屬性的時候被呼叫

# __get__:在讀取屬性的時候被呼叫

# __delete__:在刪除屬性的時候被呼叫

class

descriptor

():def

__get__

(self, instance, owner):

print("get")

def__set__

(self, instance, value):

print("set")

def__delete__

(self, instance):

print("delete")

class

a():

x = descriptor()

a = a()

a.xa.x = 1

del a.x

"""get

setdelete

"""

class

attr

():def

__init__

(self, name, name_type):

self.name = name

self.name_type = name_type

def__get__

(self, instance, owner):

return instance.__dict__[self.name]

def__set__

(self, instance, value):

ifnot isinstance(value, self.name_type):

raise typeerror("expected an {}".format(self.name_type))

instance.__dict__[self.name] = value

def__delete__

(self, instance):

del instance.__dict__[self.name]

# p.name='jack' #名字必須是str

# p.age=18 #年齡必須是int

class

person

(): name = attr("name", str)

age = attr("age", int)

p=person()

p.name= "tom"

p.age = 123

參考:

面試python如果你說出這幾招,讓你瞬間牛叉

PYTHON類的特殊方法

例項1 python view plain copy coding utf 8 class firstdemo object 這裡是乙個doc a 10 類屬性 def demo self 第乙個方法 pass def demo2 self 第二個方法 pass print firstdemo.di...

Python類的特殊方法

doc描述類的資訊 class foo object 單引號和雙引號都可以 這裡描述類的資訊 def func self passprint foo.doc 這裡描述類的資訊 call物件後面加括號,觸發執行 class foo object defcall self,args,kwargs pri...

Python類的特殊方法

特殊方法,也稱為魔術方法 特殊方法都是使用 開頭和結尾的 特殊方法一般不需要我們手動呼叫,需要在一些特殊情況下自動執行 定義乙個person類 class person object 人類 def init self,name age self.name name self.age age str ...