子类继承父类self.variable

时间:2019-03-06 21:47:00

标签: python python-3.x class inheritance

我不确定是否已问过这个问题,因为我看不到任何类似的问题。

以下是我的问题:

class Parent(object):
    def __init__(self,**kwargs):
        self.name = kwargs.get('name',None)
        self.age = kwargs.get('age',None)
        self.year = '1995'
        print(self.name,self.age,self.year)

class Child(Parent):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.parent_name = self.name
        self.parent_age = self.age
        self.parent_year = self.year
        print("Parent Details: ",self.parent_name,self.parent_age,self.parent_year)

>>> res = Parent(name='Derek',age=22)
Derek 22 1994
>>> res2 = Child()
None None 1994

我的问题是,为什么子类返回None?我已经使用了super()来继承父init类。以下是我的期望以及如何实现?

>>> res = Parent(name='Derek',age=22)
Derek 22 1994
>>> res2 = Child()
Parent Details: Derek 22 1994

1 个答案:

答案 0 :(得分:1)

从广义上讲,继承涉及类级别的概念。考虑这个父类:

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.datastax.driver.core.Cluster

package object connector {

  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()

  implicit val executionContext = executionContext

    implicit val session = Cluster
    .builder
      .addContactPoints("localhost")
      .withPort(9042)
      .build()
      .connect()


}

现在考虑这个子班:

import akka.stream.alpakka.cassandra.scaladsl.CassandraSource
import akka.stream.scaladsl.Sink
import com.datastax.driver.core.{Row, Session, SimpleStatement}

import scala.collection.immutable
import scala.concurrent.Future

object CassandraService {

    def selectFromCassandra()() = {

      val statement = new SimpleStatement(s"SELECT * FROM animals.alpakka").setFetchSize(20)
      val rows: Future[immutable.Seq[Row]] = CassandraSource(statement).runWith(Sink.seq)

      rows.map{item =>
       print(item)

      }
    }
}

那你就可以写

class Parent(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.year = '1995'

    def eat(self, food):
        print("I ate {}".format(food))

现在class Child(Parent): def __init__(self, name, age, p): super().__init__(name, age) self.parent_name = p.name self.parent_age = p.age self.parent_year = p.year # Or, since you can already access the name, age, and year of # an instance of Parent, just save the instance directly: self.parent = p p = Parent("Derek", 22) c = Child("Didi", 9, p) ,但c.parent_name == "Derek"c.parent_age == 22。您明确地告诉 c.name == "Didi",迪迪的父母是谁;不涉及继承。 (由于调用了c.age == 9,因此继承{em> 涉及设置Childname属性,但这是一种奇怪的类层次结构。{{1} }是age的子类,但这并不能很好地模拟现实世界:并非所有孩子都是父母。)

使用super().__init__方法可以实现继承。没有Child方法,因此,当您调用Parent时,会发生eat的调用,并以Child.eat实例作为其第一个参数。

c.eat("apple")

继承应用于为“ is-a”关系建模;如果Parent.eat继承自Child,则出于所有意图和目的,>>> p.eat("apple") "I ate apple" >>> c.eat("apple") "I ate apple" 的实例应该在任何可用的B实例的地方都可用。您在此处的使用违反了该规定; A有一个父母,但不一定是父母本身,因此B不应从A继承。更合理的建模将只涉及一个类:

Child