기본 제공 Python 유형에 사용자 지정 메서드 / 속성을 추가 할 수 있습니까?
예를 들어, helloWorld()Python의 dict 유형에 메소드를 추가하고 싶다고 가정 해보십시오. 할 수 있습니까?
JavaScript에는 이러한 방식으로 작동하는 프로토 타입 객체가 있습니다. 디자인이 나쁘고 dict 객체를 서브 클래 싱해야하지만 그 다음에는 서브 클래스에서만 작동하고 앞으로의 모든 사전에서 작동하기를 원합니다.
자바 스크립트에서 어떻게 다운되는지는 다음과 같습니다.
String.prototype.hello = function() {
alert("Hello, " + this + "!");
}
"Jed".hello() //alerts "Hello, Jed!"
다음은 더 많은 예제가있는 유용한 링크입니다. http://www.javascriptkit.com/javatutors/proto3.shtml
메서드를 원래 유형에 직접 추가 할 수 없습니다. 그러나 유형을 하위 클래스로 분류 한 다음 내장 / 전역 네임 스페이스에서 대체하여 원하는 대부분의 효과를 얻을 수 있습니다. 안타깝게도 리터럴 구문으로 생성 된 객체는 계속해서 바닐라 유형이되고 새 메서드 / 속성을 갖지 않습니다.
다음과 같이 생겼습니다.
# Built-in namespace
import __builtin__
# Extended subclass
class mystr(str):
def first_last(self):
if self:
return self[0] + self[-1]
else:
return ''
# Substitute the original str with the subclass on the built-in namespace
__builtin__.str = mystr
print str(1234).first_last()
print str(0).first_last()
print str('').first_last()
print '0'.first_last()
output = """
14
00
Traceback (most recent call last):
File "strp.py", line 16, in <module>
print '0'.first_last()
AttributeError: 'str' object has no attribute 'first_last'
"""
예, 해당 유형을 서브 클래 싱하여. Python에서 유형 및 클래스 통합을 참조하십시오 .
아니오, 이것은 실제 딕셔너리가이 유형을 가질 것이라는 것을 의미하지 않습니다. 왜냐하면 그것은 혼란 스러울 것이기 때문입니다. 내장 유형을 서브 클래 싱하는 것이 기능을 추가하는 데 선호되는 방법입니다.
forbbidenfruit를 시도했습니다!
여기에 아주 간단한 코드가 있습니다!
from forbiddenfruit import curse
def list_size(self):
return len(self)
def string_hello(self):
print("Hello, {}".format(self))
if __name__ == "__main__":
curse(list, "size", list_size)
a = [1, 2, 3]
print(a.size())
curse(str, "hello", string_hello)
"Jesse".hello()
class MyString:
def __init__(self, string):
self.string = string
def bigger_string(self):
print(' '.join(self.string))
mystring = MyString("this is the string")
mystring.bigger_string()
산출
t h i s i s t h e s t r i n g
Python 3.7의 데이터 클래스
from dataclasses import dataclass
@dataclass
class St:
text : str
def bigger(self) -> None:
self.text = list(self.text)
print(" ".join(self.text))
mys = St("Hello")
mys.bigger()
산출
H e l l o
NOTE: this QA is marked as duplicate to this one, but IMO it asks for something different. I cannot answer there, so I am answering here.
Specifically, I wanted to inherit from str and add custom attributes. Existing answers (especially the ones saying you can't) didn't quite solve it, but this worked for me:
class TaggedString(str):
"""
A ``str`` with a ``.tags`` set and ``.kwtags`` dict of tags.
Usage example::
ts = TaggedString("hello world!", "greeting", "cliche",
what_am_i="h4cker")
(ts.upper(), ts.tags, ts.kwtags)
"""
def __new__(cls, *args, **kwargs):
return super().__new__(cls, args[0])
def __init__(self, s, *tags, **kwtags):
super().__init__()
self.tags = set(tags)
self.kwtags = kwtags
Hopefully this helps someone! Cheers,
Andres
Subclassing is the way to go in Python. Polyglot programmers learn to use the right tool for the right situation - within reason. Something as artfully constructed as Rails (a DSL using Ruby) is painfully difficult to implement in a language with more rigid syntax like Python. People often compare the two saying how similar they are. The comparison is somewhat unfair. Python shines in its own ways. totochto.
'Program Club' 카테고리의 다른 글
| Entity Framework CodeFirst를 사용하여 데이터베이스를 시드하려면 어떻게해야합니까? (0) | 2020.11.28 |
|---|---|
| 나는 두 개의 클래스가 "싸울"수있는 프로그램을 작성했습니다. (0) | 2020.11.28 |
| List vs ArrayList vs Dictionary vs Hashtable vs Stack vs Queue? (0) | 2020.11.27 |
| Pandas 데이터 프레임을 시리즈로 변환 (0) | 2020.11.27 |
| MockMvc를 SpringBootTest와 함께 사용하는 것과 WebMvcTest를 사용하는 것의 차이점 (0) | 2020.11.27 |