强制只读Python的__init__类构造函数中的参数/属性



这可能是愚蠢和重复的问题,就像Python中类级别的只读属性一样,很难理解和实现。但是有没有一种简单的方法可以阻止对象用户修改类级别定义的只读属性(而不是方法),就像其他语言只使用"Private"关键字使其无法访问?例如,在这个简单的代码中,我希望有"full_name"属性在用户初始化对象时设置为只读,并且一旦被inner-method初始化就不能更改。

class Test:
def __init__(self,fname:str,lname:str):
self.first_name = fname
self.last_name = lname
## expected to be a read only property "full_name"
self.full_name = self.__private_fullname(fname,lname)

def __private_fullname(self,name1,name2):
return name1 + ' ' + name2



# tester
name = Test('John','Watson')
print(name.full_name)   ## returns 'John Watson'
name.full_name ='someone else'   ## still user can change read-only property
print(f'Now full_name directly changed to "{name.full_name}" by object user')

根本没有办法在python中定义私有变量,但是你可以用(@property)装饰器模拟它,以实现简洁的代码目的:类似下面的代码:

class Test:
def __init__(self, fname: str, lname: str):
self.first_name = fname
self.last_name = lname
## expected to be a read only property "full_name"
self.__full_name = fname + ' ' + lname
@property
def full_name(self):
return self.__full_name

# tester
name = Test('John', 'Watson')
print(name.full_name)  ## returns 'John Watson'
# name.full_name = 'someone else'  ## still user can change read-only property
print(f'Now full_name directly changed to "{name.full_name}" by object user')

如果你试图改变full_name,你会得到这样的错误->AttributeError: can't set attribute

关键是使用@property并在setter中添加一些限制。Python中没有'private'的概念。

class Test:
def __init__(self, fname: str, lname: str):
self.first_name = fname
self.last_name = lname
@property
def full_name(self):
return f'{self.first_name} {self.last_name}'
@full_name.setter
def full_name(self, value):
print("Nope.")

person = Test(fname="asd", lname="zxc")
print(person.full_name)
person.full_name = "qwerty"  # Nope.

最新更新