本文将介绍在Python中设置只读属性?的详细情况,特别是关于python只读属性怎么设置的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于DropD
本文将介绍在Python中设置只读属性?的详细情况,特别是关于python只读属性怎么设置的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于DropDownList添加新项和设置只读属性、Python中定义只读属性、Python只读属性、Python:在python中设置两个用逗号分隔的变量值的知识。
本文目录一览:- 在Python中设置只读属性?(python只读属性怎么设置)
- DropDownList添加新项和设置只读属性
- Python中定义只读属性
- Python只读属性
- Python:在python中设置两个用逗号分隔的变量值
在Python中设置只读属性?(python只读属性怎么设置)
鉴于Python的动态性,如果无法实现,我会感到震惊:
我想更改的实现sys.stdout.write
。
我试图简单地写成这样:
original_stdoutWrite = sys.stdout.writedef new_stdoutWrite(*a, **kw): original_stdoutWrite("The new one was called! ") original_stdoutWrite(*a, **kw)sys.stdout.write = new_stdoutWrite
但这告诉我AttributeError: ''file'' object attribute ''write'' is read-only
。
这是防止我做可能(可能)愚蠢的事情的好尝试,但是我真的很想继续做下去。我怀疑解释器有某种可以修改的查找表,但我在Google上找不到类似的表。__setattr__
也不起作用-
它返回了与只读属性完全相同的错误。
我很想寻找一个Python
2.7解决方案,如果那很重要的话,尽管没有理由拒绝抛出适用于其他版本的答案,因为我怀疑将来其他人会在这里看到有关其他版本的类似问题。
答案1
小编典典尽管具有动态功能,但Python不允许猴子修补内置类型,例如file
。它甚至可以通过修改__dict__
这种类型的来防止您这样做—该__dict__
属性返回包装在只读代理中的字典,因此分配file.write
和file.__dict__[''write'']
失败都会失败。至少有两个很好的理由:
C代码期望
file
内置类型与PyFile
类型结构以及内部使用file.write
的PyFile_Write()
函数相对应。Python对类型实现属性访问的缓存,以加快方法查找和实例方法的创建。如果允许直接分配给类型dict,则此缓存将被破坏。
用Python实现的类当然可以使用猴子补丁,它可以很好地处理动态修改。
但是,如果您真的知道自己在做什么,则可以使用低级API,例如,ctypes
可以挂接到实现并获取类型dict。例如:
# WARNING: do NOT attempt this in production code!import ctypesdef magic_get_dict(o): # find address of dict whose offset is stored in the type dict_addr = id(o) + type(o).__dictoffset__ # retrieve the dict object itself dict_ptr = ctypes.cast(dict_addr, ctypes.POINTER(ctypes.py_object)) return dict_ptr.contents.valuedef magic_flush_mro_cache(): ctypes.PyDLL(None).PyType_Modified(ctypes.py_object(object))# monkey-patch file.writedct = magic_get_dict(file)dct[''write''] = lambda f, s, orig_write=file.write: orig_write(f, ''42'')# flush the method cache for the monkey-patch to take effectmagic_flush_mro_cache()# magic!import syssys.stdout.write(''hello world\n'')
DropDownList添加新项和设置只读属性
DropDownList默认的属性里没有只读,设置 Enabled="false"可以使DropDownList禁用(只读)。
设置从数据库获取的默认选项可以用DropDownList.Items.Insert(0,new ListItem("text","value"));插入新的一项,0是插入的索引位置为第一个。
效果图:
aspx代码:
<asp:DropDownListrunat="server" ID="ddlController1" Enabled="false">
<asp:ListItem Text="First" Value="First"></asp:ListItem>
<asp:ListItem Text="Second" Value="Second"></asp:ListItem>
<asp:ListItem Text="Third" Value="Third"></asp:ListItem>
<asp:ListItem Text="Fourth" Value="Fourth"></asp:ListItem>
</asp:DropDownList>
aspx.cs代码
//获取datatable
DataTable dt5 = new DataTable();
dt5 = ClientService.Instance.GetControlledInfo(Convert.ToInt32(ClientID));
//判断是否有数据
if (dt5.Rows.Count > 0)
{
string CreditStatus = dt5.Rows[0]["CreditStatus"].ToString();
string CreditAmount = dt5.Rows[0]["CreditAmount"].ToString();
string ServiceFeeRate = dt5.Rows[0]["ServiceFeeRate"].ToString();
string FuelFeeRate = dt5.Rows[0]["FuelFeeRate"].ToString();
//在第一条的位置插入数据库取到的值 0为插入的位置,ListIterm(显示的text,选择的Value)
ddlController1.Items.Insert(0, new ListItem(CreditStatus, CreditStatus));
ddlController2.Items.Insert(0, new ListItem(CreditAmount, CreditAmount));
ddlController3.Items.Insert(0, new ListItem(ServiceFeeRate, ServiceFeeRate));
ddlController4.Items.Insert(0, new ListItem(FuelFeeRate, FuelFeeRate));
}
else
{
ddlController1.Items.Insert(0, new ListItem("没有相关信息", "0"));
ddlController2.Items.Insert(0, new ListItem("没有相关信息", "0"));
ddlController3.Items.Insert(0, new ListItem("没有相关信息", "0"));
ddlController4.Items.Insert(0, new ListItem("没有相关信息", "0"));
}
Python中定义只读属性
Python是面向对象(OOP)的语言, 而且在OOP这条路上比Java走得更彻底, 因为在Python里, 一切皆对象, 包括int, float等基本数据类型.
在Java里, 若要为一个类定义只读的属性, 只需要将目标属性用private修饰, 然后只提供getter()而不提供setter(). 但Python没有private关键字, 如何定义只读属性呢? 有两种方法, 第一种跟Java类似, 通过定义私有属性实现. 第二种是通过__ setattr__.
通过私有属性
用私有属性+@property定义只读属性, 需要预先定义好属性名, 然后实现对应的getter方法.,如果对属性还不懂。
class Vector2D(object):
def __init__(self, x, y):
self.__x = float(x)
self.__y = float(y)
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
if __name__ == "__main__":
v = Vector2D(3, 4)
print(v.x, v.y)
v.x = 8 # error will be raised.
输出:
(3.0, 4.0)
Traceback (most recent call last):
File ...., line 16, in <module>
v.x = 8 # error will be raised.
AttributeError: can''t set attribute
可以看出, 属性x是可读但不可写的.
通过 __ setattr__ 当我们调用obj.attr=value时发生了什么?
很简单, 调用了obj的__ setattr__方法. 可通过以下代码验证:
class MyCls():
def __init__(self):
pass
def __setattr__(self, f, v):
print ''setting %r = %r''%(f, v)
if __name__ == ''__main__'':
obj = MyCls()
obj.new_field = 1
输出:
setting ''new_field'' = 1
1
PS:遇到问题没人解答?需要Python学习资料?可以加点击下方链接自行获取 note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76
所以呢, 只需要在__ setattr__ 方法里挡一下, 就可以阻止属性值的设置, 可谓是釜底抽薪. 代码:
# encoding=utf8
class MyCls(object):
readonly_property = ''readonly_property''
def __init__(self):
pass
def __setattr__(self, f, v):
if f == ''readonly_property'':
raise AttributeError(''{}.{} is READ ONLY''.\
format(type(self).__name__, f))
else:
self.__dict__[f] = v
if __name__ == ''__main__'':
obj = MyCls()
obj.any_other_property = ''any_other_property''
print(obj.any_other_property)
print(obj.readonly_property)
obj.readonly_property = 1
输出:
any_other_property
readonly_property
Traceback (most recent call last):
File "...", line 21, in <module>
obj.readonly_property = 1
...
AttributeError: MyCls.readonly_property is READ ONL
Python只读属性
我不知道何时属性应该是私有的,是否应该使用属性。
我最近读到,setter和getters不是pythonic,我应该使用属性装饰器。没关系。
但是,如果我有属性,那一定不能从类外部设置,而是可以读取的(只读属性)。这个属性应该是私有的self._x
吗?我所说的私有是指下划线吗?如果是,那么不使用getter怎么读?我现在知道的唯一方法是写
@property
def x(self):
return self._x
这样我就可以读取属性,obj.x
但是我无法设置它,obj.x = 1
所以很好。
但是我真的应该关心设置不应该设置的对象吗?也许我应该离开它。但是再说一次,我不能使用下划线,因为obj._x
对用户而言,阅读很奇怪,因此我应该使用下划线obj.x
,然后,用户又一次不知道他一定不能设置此属性。
您的看法和做法是什么?
Python:在python中设置两个用逗号分隔的变量值
python之间的区别是什么:
a, b = c, max(a, b)
和
a = cb = max(a, b)
在同一行上设置两个变量分配有什么作用?
答案1
小编典典你的两个片段做不同的事情:有尝试a
,b
和c
等于7
,8
和9
分别。
第一个片段设置三个变量9
,8
和9
。换句话说, 在之前 将max(a,b)
计算分配给的值。本质上,所有要做的就是将两个值压入堆栈。变量,然后在弹出时将它们分配给这些值。 __a``c``a, b = c, max(a,b)``a``b
另一方面,运行第二个代码段会将所有三个变量设置为9
。这是因为a
被设置为指向进行c
函数调用之前的值max(a, b)
。
今天关于在Python中设置只读属性?和python只读属性怎么设置的介绍到此结束,谢谢您的阅读,有关DropDownList添加新项和设置只读属性、Python中定义只读属性、Python只读属性、Python:在python中设置两个用逗号分隔的变量值等更多相关知识的信息可以在本站进行查询。
本文标签: