[英]python - another class inside constructor
I'm new to Python and I'm having a hard time understanding how I can do the following in Python (eg how I would do in Java) 我是Python的新手,我很难理解如何在Python中执行以下操作(例如,在Java中的操作方式)
class Person{
private String name;
private Address address;
public Person(String xyz, Address a) {
this.name = xyz;
this.address = a;
}
....
}
I don't know why you think there is another class inside the constructor, but above Java could would look like this in Python: 我不知道为什么您认为构造函数中还有另一个类,但是在Java之上,Python中看起来可能像这样:
class Person (object):
def __init__ (self, xyz, a):
self.name = xyz
self.address = a
As a dynamically typed language, Python does not need to know what types look like when the code compiles. 作为一种动态类型化的语言,Python无需知道代码编译时的类型。 Instead, it dynamically creates objects, and adds properties whenever needed. 相反,它动态创建对象,并在需要时添加属性。 This allows you not only to add instance fields in the initializer that were not declared before, but also allows you to add things after an object was created: 这不仅允许您在初始化器中添加之前未声明的实例字段,而且还允许您在创建对象之后添加内容:
x = Person("poke", "My address")
x.phoneNumber = "012345679"
Like @poke mentioned, you can do: 就像提到的@poke一样,您可以执行以下操作:
class Person (object):
def __init__ (self, xyz, a):
self.name = xyz
self.address = a
If you mean also having the default constructor, then you can have something like: 如果您还想拥有默认的构造函数,那么您可以拥有类似以下内容的东西:
class Person (object):
def __init__ (self, xyz=None, a=None):
self.name = xyz
self.address = a
Which will allow you to call the constructor with no arguments. 这将允许您不带参数调用构造函数。
You can use the constructor as: 您可以将构造函数用作:
p = Person("yadda","bla")
or 要么
p = Person()
something like this: 像这样的东西:
class Person(object):
def __init__(self, xyz, a):
self.name = xyz
self.address = a
# ...
now, of course you can define a new class inside the constructor: 现在,您当然可以在构造函数中定义一个新类:
class Person(object):
def __init__(self, xyz, a):
self.name = xyz
self.address = a
class Glass(object):
def __init__(self):
self.glass_name = xyz
#... whatever - but what purpose would this serve?
# ...
Python doesn't really have private
variables, everyone is treated like adults in regards to member access however you would probably end up implementing getter / setter methods anyway. Python确实没有private
变量,在成员访问方面,每个人都被视为成年人,但是无论如何,您最终可能会实现getter / setter方法。 Note the _
variable name prefix is just a PEP-8 naming convention for "private" variables although it doesn't actually stop access to them. 注意_
变量名前缀只是“私有”变量的PEP-8命名约定,尽管它实际上并没有停止对它们的访问。
class Person(object): # subclass object for a new-style class
def __init__(self, name, address):
self._name = name
self._address = address
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def address(self):
return self._address
@address.setter
def address(self, address):
self._address = address
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.