简体   繁体   English

如何使父 class object 指代子 class?

[英]How to make a parent class object referring to a child class?

Like in java or C# where we can create an object like就像在 java 或 C# 中我们可以创建一个 object 一样

Account obj = new SavingsAccount();

where Account is the parent class and SavingsAccount is the child class其中Account是父 class 而SavingsAccount是子 class

How do I do the same thing with python?我如何用 python 做同样的事情?

basically I'm trying to do is this https://repl.it/@MushfiqurRahma1/Polymorphic-Object基本上我想做的是这个https://repl.it/@MushfiqurRahma1/Polymorphic-Object

Python is dynamically typed: names refer to objects without any notion of type being involved. Python 是动态类型的:名称指的是不涉及任何类型概念的对象。 You just have你只是有

>>> class Account: pass
...
>>> class SavingsAccount(Account): pass
...
>>> obj = SavingsAccount()

Each object stores a reference to its own type每个 object 都存储对其自身类型的引用

>>> type(obj)
<class '__main__.SavingsAccount'>

and each type has a referent to its method resolution order (MRO)并且每种类型都有其方法解析顺序(MRO)的引用

>>> type(obj).__mro__
(<class '__main__.SavingsAccount'>, <class '__main__.Account'>, <class 'object'>)

Instance attributes are not "compartmentalized" according to the class that "defines" them;根据“定义”实例属性的 class,实例属性没有“划分”; each attribute simply exists on the instance itself, without reference to any particular class.每个属性仅存在于实例本身上,而不涉及任何特定的 class。

Methods exist solely in the classes themselves;方法只存在于类本身; when it comes time to call obj.foo() , the MRO is used to determine whose definition is used.当调用obj.foo()时,MRO 用于确定使用谁的定义。

Python uses Duck typing, which means you shouldn't really care about the class in the Left side of the assignment. Python 使用 Duck 类型,这意味着您不应该真正关心作业左侧的 class。 Just instantiate the Child class and you should already be able to use it's parent “interface” to do stuff like dynamic method calls.只需实例化子 class,您应该已经能够使用它的父“接口”来执行诸如动态方法调用之类的操作。

Python is a loosely typed language. Python 是一种松散类型的语言。 That means you don't have to specify your variable types.这意味着您不必指定变量类型。 You could just do something like:你可以这样做:

class Account():
    def deposit():
        pass
class SavingsAccount(Account):
    pass

obj = SavingsAccount()
obj.deposit(20)

EDIT : As chepner pointed out: Python is strongly typed, but also dynamically typed: type is associated with an object, not the name referring to an object.编辑:正如chepner指出的那样: Python is strongly typed, but also dynamically typed: type is associated with an object, not the name referring to an object.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM