为类中可能无法计算的成员设置值可以通过构造函数、属性和方法来实现。
示例代码:
class MyClass:
def __init__(self, member1, member2):
self.member1 = member1
self.member2 = member2
self.member3 = "固定值"
obj = MyClass("value1", "value2")
print(obj.member1) # 输出:value1
print(obj.member2) # 输出:value2
print(obj.member3) # 输出:固定值
示例代码:
class MyClass:
def __init__(self, member1, member2):
self.member1 = member1
self.member2 = member2
@property
def member3(self):
return "固定值"
obj = MyClass("value1", "value2")
print(obj.member1) # 输出:value1
print(obj.member2) # 输出:value2
print(obj.member3) # 输出:固定值
示例代码:
class MyClass:
def __init__(self, member1, member2):
self.member1 = member1
self.member2 = member2
def get_member3(self):
return "固定值"
obj = MyClass("value1", "value2")
print(obj.member1) # 输出:value1
print(obj.member2) # 输出:value2
print(obj.get_member3()) # 输出:固定值
以上是三种常用的方式来为类中无法计算的成员设置值。根据具体的需求和场景,选择合适的方式来实现。
领取专属 10元无门槛券
手把手带您无忧上云