python 진급평론 대상 을 향 한 진급
9468 단어 python대상 을 향 하 다진급 하 다
1.isinstance 와 issubclass
class Foo:
pass
class Son(Foo):
pass
s = Son()
# , ( , )
print(isinstance(s,Son))
print(isinstance(s,Foo))
#type
print(type(s) is Son)
print(type(s) is Foo)
# , ( , )
print(issubclass(Son,Foo))
print(issubclass(Son,object))
print(issubclass(Foo,object))
print(issubclass(int,object))
반사반사 개념 은 Smith 가 1982 년 에 처음으로 제기 한 것 으로 프로그램 이 그 자체 의 상태 나 행 위 를 방문 하고 검 측 하 며 수정 할 수 있 는 능력(자성)을 말한다.이 개념의 제 기 는 곧 컴퓨터 과학 분야 에서 응용 반사 성에 관 한 연 구 를 불 러 일 으 켰 다.이 는 먼저 프로그램 언어의 디자인 분야 에 사용 되 었 고 Lisp 와 대상 을 대상 으로 하 는 데 성 과 를 거 두 었 다.
python 대상 에 대한 반사:문자열 형식 으로 대상 과 관련 된 속성 을 조작 합 니 다.python 의 모든 사물 은 대상(반사 사용 가능)
반사 가능 한 네 가지 함수:hasattr,getattr,setattr,delattr
다음 방법 은 클래스 와 대상(모든 것 이 대상 이 고 클래스 자체 도 하나의 대상)에 적용 된다.
class Foo:
def __init__(self):
self.name = 'egon'
self.age = 73
def func(self):
print(123)
egg = Foo()
# :
#hasattr
#getattr
# print(hasattr(egg,'name'))
print(getattr(egg,'name'))
if hasattr(egg,'func'): # bool
Foo_func = getattr(egg,'func') # ,
# , , hasattr
Foo_func()
# :
#setattr
# setattr(egg,'sex',' ')
# print(egg.sex)
# def show_name(self):
# print(self.name + ' sb')
# setattr(egg,'sh_name',show_name)
# egg.sh_name(egg)
# show_name(egg)
# egg.sh_name()
#delattr
# delattr(egg,'name')
# print(egg.name)
# print(egg.name)
# egg.func()
# print(egg.__dict__)
#
# 、
1
class Foo:
f = 123 #
@classmethod
def class_method_demo(cls):
print('class_method_demo')
@staticmethod
def static_method_demo():
print('static_method_demo')
# if hasattr(Foo,'f'):
# print(getattr(Foo,'f'))
print(hasattr(Foo,'class_method_demo'))
method = getattr(Foo,'class_method_demo')
method()
print(hasattr(Foo,'static_method_demo'))
method2 = getattr(Foo,'static_method_demo')
method2()
#
반사 예시 2
import my_module
# print(hasattr(my_module,'test'))
# # func_test = getattr(my_module,'test')
# # func_test()
# getattr(my_module,'test')()
#import
from my_module import test
def demo1():
print('demo1')
import sys
print(__name__) #'__main__'
print(sys.modules)
#'__main__': <module '__main__' from 'D:/Python /S6/day26/6 3.py'>
module_obj =sys.modules[__name__] #sys.modules['__main__']
# module_obj : <module '__main__' from 'D:/Python /S6/day26/6 3.py'>
print(module_obj)
print(hasattr(module_obj,'demo1'))
getattr(module_obj,'demo1')()
#
3
#
#
# :
def register():
print('register')
def login():
pass
def show_shoppinglst():
pass
#
print(' , ')
ret = input(' , : ')
import sys
print(sys.modules)
# my_module = sys.modules[__name__]
# if hasattr(my_module,ret):
# getattr(my_module,ret)()
if ret == ' ':
register()
elif ret == ' ':
login()
elif ret == 'shopping':
show_shoppinglst()
4
def test():
print('test')
3.클래스 의 내장 함수1、__str__와repr__
class Foo:
def __init__(self,name):
self.name = name
def __str__(self):
return '%s obj info in str'%self.name
def __repr__(self):
return 'obj info in repr'
f = Foo('egon')
# print(f)
print('%s'%f)
print('%r'%f)
print(repr(f)) # f.__repr__()
print(str(f))
# , str,
# str , repr
# %s %r __str__ __repr__
# ,repr str
#
# 。 str repr : repr
2、__del__
class Foo:
def __del__(self):
print(' ')
f = Foo()
print(123)
print(123)
print(123)
# , , 。
# : , Python , , Python , , 。
3.아 이 템 시리즈__getitem__\__setitem__\__delitem__
class Foo:
def __init__(self):
self.name = 'egon'
self.age = 73
def __getitem__(self, item):
return self.__dict__[item]
def __setitem__(self, key, value):
# print(key,value)
self.__dict__[key] = value
def __delitem__(self, key):
del self.__dict__[key]
f = Foo()
print(f['name'])
print(f['age'])
f['name'] = 'alex'
# del f['name']
print(f.name)
f1 = Foo()
print(f == f1)
4、__new__
# class A:
# def __init__(self): # self
# print('in init function')
# self.x = 1
#
# def __new__(cls, *args, **kwargs):
# print('in new function')
# return object.__new__(A, *args, **kwargs)
# a = A()
# b = A()
# c = A()
# d = A()
# print(a,b,c,d)
#
class Singleton:
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls, *args, **kw)
return cls._instance
one = Singleton()
two = Singleton()
three = Singleton()
go = Singleton()
print(one,two)
one.name = 'alex'
print(two.name)
5、__call__
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('__call__')
obj = Foo() # __init__
obj() # __call__
Foo()() # __init__ __call__
# , : = () ; __call__ , : () ()()
6、__len__,__hash__
class Foo:
def __len__(self):
return len(self.__dict__)
def __hash__(self):
print('my hash func')
return hash(self.name)
f = Foo()
print(len(f))
f.name = 'egon'
print(len(f))
print(hash(f))
7、__eq__
class A:
def __init__(self):
self.a = 1
self.b = 2
def __eq__(self,obj):
if self.a == obj.a and self.b == obj.b:
return True
a = A()
b = A()
print(a == b)
#__eq__ ==
8.내장 함수 인 스 턴 스
class FranchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = [' ',' ',' ',' ']
def __init__(self):
self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
for suit in FranchDeck.suits]
def __len__(self):
return len(self._cards)
def __getitem__(self, item):
return self._cards[item]
deck = FranchDeck()
print(deck[0])
from random import choice
print(choice(deck))
print(choice(deck))
class FranchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = [' ',' ',' ',' ']
def __init__(self):
self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
for suit in FranchDeck.suits]
def __len__(self):
return len(self._cards)
def __getitem__(self, item):
return self._cards[item]
def __setitem__(self, key, value):
self._cards[key] = value
deck = FranchDeck()
print(deck[0])
from random import choice
print(choice(deck))
print(choice(deck))
from random import shuffle
shuffle(deck)
print(deck[:5])
2
class Person:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def __hash__(self):
return hash(self.name+self.sex)
def __eq__(self, other):
if self.name == other.name and other.sex == other.sex:return True
p_lst = []
for i in range(84):
p_lst.append(Person('egon',i,'male'))
print(p_lst)
print(set(p_lst))
#
이상 이 python 진급대상 을 대상 으로 진급 하 는 것 은 바로 편집장 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.여러분 께 참고 가 되 고 여러분 들 이 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.