Last active
September 15, 2019 07:15
-
-
Save DeanLa/1998f99121f2c3a9c6544da6982171a1 to your computer and use it in GitHub Desktop.
Intermediate Class Tricks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Get attributes from contained class | |
class A: | |
def __init__(self, a, b, ): | |
self.a = a | |
self.b = b | |
class B: | |
def __init__(self, c, acls): | |
print("Y") | |
self.c = c | |
self.acls = acls | |
def __getattr__(self, attr): | |
print('Hello') | |
ret = getattr(self.acls, attr) | |
return ret | |
x = A('a', 'b') | |
y = B('c', x) | |
print(y.b) | |
print(y.a) | |
# Set attributes with dict | |
class C: | |
def __init__(self, a, conf): | |
for k, v in conf.items(): | |
setattr(self, k, v) | |
self.a = a | |
conf = {'con': '1.1.1.1', 'data': [1, 2, 3, 4]} | |
c = C('a', conf) | |
print(c.a) | |
print(c.con) | |
print(c.data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment