我有一个 python 类,可以通过两种不同的方式实例化。我可以创建 type1 类或 type2 类...但是如何在实例化过程中仅更改一个特定的默认值?
class MyClass:
DEFAULT_PARAMS = {
"type_1": {
"name": "smith", # Stock name
"region": "newman",
"country": "USA"
},
"type_2": {
"age": "34", # Stock name
"gender": "male",
"income": "100":
}
}
m = MyClass("type_1")
m = MyClass("type_2")
假设我想创建一个 type_1 类,但我想将国家/地区更改为(例如加拿大)......正确的语法是什么?
最佳答案
如果 type_1
和 type_2
必须属于同一类,那么看起来这是 class inheritance 的一个很好的用例:
class MyClass:
pass
class Type1(MyClass):
def __init__(self, name="smith", region="newman", country="USA"):
self.name = name
self.region = region
self.country = country
class Type2(MyClass):
def __init__(self, age="34", gender="male", income="100"):
self.age = age
self.gender = gender
self.income = income
您可以覆盖默认属性,如下所示:
x = Type1(country="CANADA")
在此场景中,Type1
和 Type2
的实例也是 MyClass
的实例:
x = Type1(country="CANADA")
print(isinstance(x, MyClass)) # True
y = Type2()
print(isinstance(y, MyClass)) # True
<小时/>
另外,这只是我的观点,但我发现将 age
和 venue
设置为字符串很奇怪。也许它们应该是数字?
class Type2(MyClass):
def __init__(self, age=34, gender="male", income=100):
self.age = age
self.gender = gender
self.income = income
关于python - 如何更改实例化Python类的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56819280/