[英]how to change a default parameter in instantiating a python class?
I have a python class that can be instantiated in two different ways. 我有一个可以用两种不同方式实例化的python类。 I can either create a type1 class or type2 class.... But how could I change only one particular default during instantiation? 我可以创建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")
Let's say I want to create a class of type_1, but I want to change the country to (eg CANADA).... What is the proper syntax for that? 假设我要创建一个类型为type_1的类,但是要将国家/地区更改为(例如CANADA)。...正确的语法是什么?
If both type_1
and type_2
must belong to the same class, it looks like this is a good use case for class inheritance : 如果type_1
和type_2
必须都属于同一个类,那么这似乎是类继承的一个好用例:
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
You can override default attributes like such: 您可以覆盖默认属性,例如:
x = Type1(country="CANADA")
In this scenario, instances of Type1
and Type2
are also instances of MyClass
: 在这种情况下, Type1
和Type2
的实例也是MyClass
实例:
x = Type1(country="CANADA")
print(isinstance(x, MyClass)) # True
y = Type2()
print(isinstance(y, MyClass)) # True
Also, this is just my opinion, but I find it weird that age
and income
are set to strings. 同样,这只是我的看法,但是我发现age
和income
设置得很奇怪。 Maybe they should be numbers instead? 也许应该改为数字?
class Type2(MyClass):
def __init__(self, age=34, gender="male", income=100):
self.age = age
self.gender = gender
self.income = income
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.