1

This is by documentation:

NewClass = types.new_class("NewClassName", (SuperClass,), kwds = { "namespace" : my_ontology })

I don't understand why the code doesn't work. I have written:

NewClass = types.new_class("NewClassName", (Example,), kwds = { "namespace" : onto })

I have also try the code that doesn't work from url: Owlready2 dynamic class generation

types.new_class("NewClassName", (onto["ParentClass"],))

I don't understand the expression (onto["ParentClass"],). Then I don't understand how to create dynamically individuals. It is possible to do it?

Can I have a short simple script of example that works with a class and an individual?

Milan Cermak
  • 7,476
  • 3
  • 44
  • 59
Hamico
  • 11
  • 3

1 Answers1

2
  1. I have just written that code and tested it:
from owlready2 import *

# check that the base class is accessible
print(Thing)  # owl.Thing

my_onto = get_ontology('http://test/qwerty')

with my_onto:
    my_new_class = types.new_class("NewClassName", (Thing,))  # make a class

print(my_new_class)  # qwerty.NewClassName

my_obj = my_new_class("myObjName")  # make an instance

print(my_obj)  # qwerty.myObjName

Note to derive custom class from owlready2.Thing (as in my case) or any of it's subclasses.

Creating individuals is simple as making ordinal python instances (use variable holding the reference to created class (my_new_class in my case) as constructor, so call it to get a new instance). The call is not required to be placed inside the with my_onto: block.

So the newly created entities are accessible via:

  • class_var = my_onto.NewClassName
  • class_var = my_onto["NewClassName"] # returns None if you pass wrong string
  • obj_var = my_onto.myObjName
  • obj_var = my_onto["myObjName"]

Note that an instance is not created if already exists. So the code below always returns True:

my_onto["myObjName"] is my_onto["myObjName"]  # True

I did that with my Python3.7 and Owlready2 v0.23 recently released (as of pip install -U owlready2 reported).

  1. The code (onto["ParentClass"],) just obtains desired base class from the ontology onto and packs it into a tuple (note the syntax (a,) to create one-element tuple).
Samantra
  • 65
  • 1
  • 8