如何在实例化Python类中更改默认参数



我有一个可以以两种不同方式实例化的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_1type_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

您可以像这样覆盖默认属性:

x = Type1(country="CANADA")

在这种情况下,Type1Type2的实例也是MyClass的实例:

x = Type1(country="CANADA")
print(isinstance(x, MyClass)) # True
y = Type2()
print(isinstance(y, MyClass)) # True

另外,这只是我的意见,但是我发现ageincome设置为字符串很奇怪。也许它们应该是数字?

class Type2(MyClass):
   def __init__(self, age=34, gender="male", income=100):
       self.age = age
       self.gender = gender
       self.income = income

最新更新