-
Notifications
You must be signed in to change notification settings - Fork 44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
python类继承,PHP怎么实现 #34
Comments
// 假设test.php和Animal.py在同一个目录下
$sys = PyCore::import('sys');
PyCore::import('sys')->path->append(__DIR__);
$pycode = <<<CODE
from t import Animal
class Cat(Animal):
def __init__(self,name,age,sex):
super(Cat, self).__init__(name,age) # 不要忘记从Animal类引入属性
self.sex=sex
def call(self):
print(f'name {self.name}, age {self.age}, sex {self.sex}')
CODE;
$globals = new PyDict();
PyCore::exec($pycode, $globals);
echo $globals['Cat']('T', 0, 0)->call(), PHP_EOL;
from Animal import Animal
class Cat(Animal):
def __init__(self,name,age,sex):
super(Cat, self).__init__(name,age) # 不要忘记从Animal类引入属性
self.sex=sex
def call(self):
print(f'name {self.name}, age {self.age}, sex {self.sex}')
<?php
// 假设test.php和Animal.py在同一个目录下
$sys = PyCore::import('sys');
PyCore::import('sys')->path->append(__DIR__);
echo PyCore::import('Cat')->Cat('T', 0, 0)->call(), PHP_EOL; |
没想通为什么要这样做,phpy 是可以让你创建 Python 类的对象,调用方法,而不是让 PHP 写 Py 代码。如果单纯的语言语法问题,PHP 应该用 PHP 的语法,与 Python 没有任何关系。 我能想到的只有一种情况一定要写一个 Py 子类去继承,大概是父类是一个抽象类,子类一定要继承后才能被构造。 import abc
class Animal(abc.ABC):
@abc.abstractmethod
def speak(self):
pass 这个情况是无法用 # dog.py
class Dog(Animal):
def speak(self):
print('woof') $dog = PyCore::import("dog");
$obj = $dog->Dog();
$obj->speak(); |
最新的 1.0.8 支持 PHP 类继承 Python 类了 实例use phpy\PyClass;
#[Inherit('Animal', 'animal')]
class Dog extends PyClass
{
function __construct(string $name, int $age)
{
parent::__construct();
$this->color = 'black';
$this->super()->__init__($name, $age);
}
function speak(string $name): void
{
echo "Dog $name, color: {$this->self()->color}, speak: wang wang wang\n";
$this->super()->speak('dog');
}
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
例如Python有个类
php怎么实现Cat类继承Animal呢?
The text was updated successfully, but these errors were encountered: